Marker interface or boolean method to identify object capabilities?

api-design, java, marker-interfaces, oop, properties

Solution

Marker interfaces are inherited in class hierarchy, so they have limited capabilities (you cannot "remove" this marker interface for some particular subclass) and I cannot recommend them (Cloneable is a bad example of this). The question is - is your property really bound to object's class, not to instance? If so, annotations are better, because they don't add additional methods into your APIs and they are easier to maintain - you just add/remove the annotation (in case of checking method, you have to check all the subclasses, whether they override it or not).

EDIT: in your case, I would ask myself question: is my property like 'is persistent' (applies for all instances of given class) or 'is visible' (applies only for some instances)

Problem

I am developing a largish hierarchy of Java classes, some of which have a particular property that I am interested in querying at runtime (the property definitely only applies to classes, not specific instances). I could create an abstract boolean method `isFooBar()` that subclasses could implement to indicate whether the property is present or not: ``` public abstract class MyBaseClass { ... public abstract boolean isFooBar(); } ``` Or alternatively I could use a marker interface `FooBarProperty` and do an `instanceof` check against the interface: ``` public class MyConcreteClass extends MyBaseClass implements FooBarProperty { ... } ``` Or I guess you could even use an annotation as suggested by AmitD: ``` @FooBarAnnotation public class MyConcreteClass extends MyBaseClass { ... } ``` What are the pros and cons of each method, and which should normally be preferred?

Original source