I see a trend lately in Java libraries and code that I thought was only plaguing Microsoft developers: naming interfaces like
ISomething. I find this very disturbing so I thought I had to react.
First thing: an interface is a type just like a class. What a type does is mainly to define the set of operations (methods) that are applicable to an instance of a class that implements this type. When dealing with references, the only thing the Java compiler cares about is the type of the reference, so that is knows if a method call is licit or not. It does not care if the type is a class or an instance. Think about the
instanceof operator: despite what the awkward name suggests, it works with interfaces as well as classes, because what it actually tests is whether a given reference is of a particular type.
So, why shouldn’t you name your interfaces beginning with the letter I?
- it breaks a fundamental OO rule, which is that you should let the users of your code know as little as possible about the implementation. If a method returns a object of type Foo, it doesn’t make any difference to the caller of this method if Foo is actually a class or en interface.
- it is redundant. If you really need to know, the documentation (written or Javadoc), or your IDE’s lookup mechanism, will tell you if it’s an interface or not
- it makes code harder to read. Which one do you prefer:
IFoo foo = getFoo();
IBar bar = (IBar) foo.getStuff();
Foo foo = getFoo();
Bar bar = (Bar) foo.getStuff();
I understand that developpers are often tempted to name interfaces like that because they know there will likely ever be only one implementation of this interface. So they have a Foo class, and it needs to implement an interface, why not name it IFoo?
Two points here:
- You don’t always need to define an interface for such a class. If you are configuring Spring beans for example, your bean references don’t need to be an interface type. Even if it is good practice to do so, there are cases (such as the one above) where it’s a perfectly valid case to use the class directly.
- Why not name your interface Foo, and your implementation something else, like DefaultFoo or SimpleFoo or BaseFoo or whatever. Or maybe just Foo, provided it’s not in the same package! If you are using a factory, no-one will ever know or care how the concrete class is named anyway.
Naming interfaces like ISomething is similar to including type name or scope in your variables names. Yuck… Please don’t bring this to Java.