Wednesday, 18 February 2009

Item 19: Use Interfaces only to define types

This item is a short one but I found it confusing, maybe because I am a java novice.

The interface defines a type for its clients. Nothing else should be used. The main topic is using interfaces with static final fields that define constants, a so called constant interface. It should not be used because it pollutes the client with implementation details. The constant interface infects the hierarchy of a client class and can never be removed in the future. It could break binary compatibility.

So if I have a class that uses an interface with constants and the class is not final, then I could not remove this interface even if I don't need it? Is this because an inherited class could use it and I don't want to break existing code. Or because I can't because it would break because of the compiled class files? The binary compatibility?

When constants are needed, then they should be defined in a class or interface that they are strongly related to. They either should be a enum type or defined in a concrete utility class that can't be instantiated. Does this mean that the enum or the utility class is really outside the interface? It seems to me that the enum class or utility class must be defined outside the interface and part of the public face of the package. It is a little confusing. It would be nice to have a complete example. Only an example of the utility class is provided.

Use static import facility introduced in 1.5 to include constants from an utility class without the qualifiers.

This item continues the advice from the previous items. But it seems to only concentrate on constants and how to handle them. Maybe this item could be called "How to define constants with interfaces" or something like it.

Timothy Wright

No comments: