0

Interfaces: It's all about contract baby ...

Posted by Guillermo GarcĂ­a on 8:50 AM in , ,
The interfaces in Java must be used to establish a contract with their implementators. So, interfaces define methods signatures. But Java allows you to define constants in the interface. Remember that in Java a constant is a static and final property (class variable) or a final local variable (but it is very unusual).

When you define a class variable in an interface, by default they are public, static and final. So, you can reach it in any part of your code using the class/interface name. Example: if you have an interface named "Constants" and inside of it you define a public, static and final variable named "PI", you can reach that constant that way: Constants.PI.

Now, if "Constants" is an interface, you can reach its variables another way: Implementing the interface, and calling directly the constant PI. This way, you simplify your code since you don't have to write the class/interface name every time.

This is a very common use of the interfaces in Java, but as far as I am concerned, it is a wrong use, as an interface is a conceptual contract or marker. Think about this: If you find a class "ChineseFood" that implements the interface "Eatable", you can say that you have a Chinese Food and you can eat it.

But now, look at this: If the same class "ChineseFood" also implements an interface named "NoodleSizesConstants" ... what can you say about it? Well, to me, any conclusion will be very confusing (in a theoric way).

The correct place for constant definition must be a regular class, not an interface. So you have to declare a class, create the public, static and final variables, and then IMPORT IT into your other classes. But now you must be wondering: Damn, now i have to use the class name every time? And the answer is NO, thanks to the "static imports" of Java 5.

With this feature, you can import any static variable or method in your class to avoid the "class name prefix" in your code. Thus, if you want to use the class "NoodelSizesConstants" in your "ChineseFood" class you must import it like this:

import static NoodleSizesConstants.BIG;
import static NoodelSizezConstants.REGULAR;
and so on ...

With "static imports", the justification for defining constants inside interfaces is obsolete, so please, use classes and statics import for constants references and this way you will make software architecture more "human readable" .

0 Comments

Copyright © 2009 ggarciao.com
- Cup of Java -
All rights reserved.