Monday, November 25, 2013

Marker Interfaces Vs Marker Annotations as Type definers

When it comes to defining types, there's always some debate between using Marker Interfaces vs Marker Annotations. To appreciate the discussion its important to understand what are marker interfaces. Well, a marker interface is merely an interface that contains "no" method declaration and it just designates the implementing class as having some unique characteristic, e.g. the Serializable interface. On the other hand, Marker annotations are just annotations whose sole purpose is also to designate a class/method/variable to have a certain characteristic. So when do you use marker interface and when would you use an annotation to define a type in java?

The key here is to understand the intent of the usage. Let me elaborate on this. We know that only classes and interfaces that implement/extend other interfaces. Clearly you must use an annotation if the marker applies to any
program element other than a class or interface, as only classes and interfaces can
be made to implement or extend an interface. But if we believe that our end requirement of type definition could be such wherein I have to supply an class of a specific type as an argument to method, one should use a Marker interface for defining this type as it would also help in comple-time checking of the client code (remember this could be achieved even with Marker Annotation but since annotation processing does not happen till run-time there is no way to know at compile time of the contract was honoured by the client class). As an extension of this point if we believe that we want to limit the use of this marker interface to elements of a particular interface the it makes sense to define the marker as a subinterface of that interface. Therefore, marker interfaces are targeted more precisely.

But its unfair to assume that Marker annotations do not have their use. Their main advantage is that Annotations are evolutionary and this is precisely a major problem with interfaces. Interfaces cannot evolve over time. Once the contract is published especially the public interfaces, its nearly impossible to change it. On the other hand annotations can evolve into a richer annotation type over time. Annotations should be used as meta-definitions and this usage also helps to create much better code processing tools.