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.
For further reading: Practical API Design Confessions of a Java Framework Architect (Jaroslav Tulach, 2008, Apress).
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 :)
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.
I think that there are two types of interfaces declared in general:
CalculationService
. I don't think that methodsgetX
should be in this sort of interface, and certainly notsetX
. They quite clearly imply implementation detail, which is not the job of this type of interface.Note: the collections classes probably fit in to type #2
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.
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