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

查看:434
本文介绍了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. a 服务描述即可。这可能类似于 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天全站免登陆