Java Interface Usage Guidelines — Are getters and

2019-01-10 22:41发布

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

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?

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.

11条回答
甜甜的少女心
2楼-- · 2019-01-10 23:03

For further reading: Practical API Design Confessions of a Java Framework Architect (Jaroslav Tulach, 2008, Apress).

查看更多
三岁会撩人
3楼-- · 2019-01-10 23:04

I used those kind of interfaces, for example we had classes with fields beginDate, endDate. Those fields were in many classes and I had one use case I need to get those dates for different objects, so I extracted interface and was very happy :)

查看更多
可以哭但决不认输i
4楼-- · 2019-01-10 23:08

The fact that the straightforward implementation of something is as a getter shouldn't stop it being in an interface if it needs to be.

查看更多
叛逆
5楼-- · 2019-01-10 23:10

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

  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.

Note: the collections classes probably fit in to type #2

查看更多
三岁会撩人
6楼-- · 2019-01-10 23:10

I don't think a bean should have an interface on top of it, in general. A javabean is an interface in the more general meaning. An Interface specifies the external contract of something more complex. A javabean's external contract and its internal representation are identical.

I wouldn't say that you shouldn't have getters in an interface, though. It makes perfect sense to have a ReadableDataThingie interface that is implemented by DataThingieBean.

查看更多
别忘想泡老子
7楼-- · 2019-01-10 23:18

Getters are used to query the state of an object - which you can really avoid when designing your interface. Read http://www.pragprog.com/articles/tell-dont-ask

查看更多
登录 后发表回答