Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marker interface or boolean method to identify object capabilities?

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?

like image 411
mikera Avatar asked Oct 07 '22 11:10

mikera


2 Answers

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)

like image 70
Kojotak Avatar answered Oct 10 '22 02:10

Kojotak


Marker interfaces doesn't have any methods. In your case your interface has a method to get the property and on the basis of this you should use interface. You can simply use this interface to hold the concrete instance of classes which implements your interface and can call the method related with property.

However, at the other end marker is used or marked and instance or hierarchy so that it would be eligible for certain features like persistence.

like image 45
rbhawsar Avatar answered Oct 10 '22 03:10

rbhawsar