Java 接口使用指南——接口中的 getter 和 setter 是坏的吗? [英] Java Interface Usage Guidelines -- Are getters and setters in an interface bad?

查看:23
本文介绍了Java 接口使用指南——接口中的 getter 和 setter 是坏的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们认为在界面中使用的最佳指南是什么?什么应该和不应该进入界面?

What do people think of the best guidelines to use in an interface? What should and shouldn't go into an interface?

我听说有人说,作为一般规则,接口只能定义行为而不是状态.这是否意味着接口不应该包含 getter 和 setter?

I've heard people say that, as a general rule, an interface must only define behavior and not state. Does this mean that an interface shouldn't contain getters and setters?

我的意见:对于 setter 来说可能不是这样,但有时我认为 getter 放在接口中是有效的.这只是为了强制实现类来实现这些 getter,从而表明客户端能够调用这些 getter 来检查某些东西,例如.

My opinion: Maybe not so for setters, but sometimes I think that getters are valid to be placed in an interface. This is merely to enforce the implementation classes to implement those getters and so to indicate that the clients are able to call those getters to check on something, for example.

推荐答案

我认为一般有两种类型的接口声明:

I think that there are two types of interfaces declared in general:

  1. 服务描述.这可能类似于 CalculationService.我不认为方法getX 应该在这种接口中,而且当然不应该setX.它们非常清楚地暗示了实现细节,这不是此类接口的工作.
  2. 一个数据模型 - 仅用于抽象系统中数据对象的实现.这些可能用于辅助测试,或者仅仅因为一些像我一样大的人记得(例如)使用持久性框架将您绑定到具有特定超类的日子(即,您会选择实现一个接口,以防万一您切换你的持久层).我认为在这种类型的接口中使用 JavaBean 方法是完全合理的.
  1. a service description. This might be something like CalculationService. I don't think that methods getX should be in this sort of interface, and certainly not setX. They quite clearly imply implementation detail, which is not the job of this type of interface.
  2. a data model - exists solely to abstract out the implementation of data objects in the system. These might be used to aid in testing or just because some people as old as me remember the days when (for example) using a persistence framework tied you down to having a particular superclasss (i.e. you would choose to implement an interface in case you switched your persistence layer). I think that having JavaBean methods in this type of interface is entirely reasonable.

注意:集合类可能适合类型#2

这篇关于Java 接口使用指南——接口中的 getter 和 setter 是坏的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆