Ive seen this pattern in many places, but have never seen it named.
I am more after a suggestion on how to name methods that implement it, as different people seem to use a different naming pattern.
Sorry i cant recall any libraries as examples but if use one as part of your answer, please name them.
public class Produce{
package private Produce(){};
Fruit isFruit(){
return null;
}
Veg isVeg(){
return null;
}
}
public class Veg extends Produce {
package private Veg(){};
Veg isVeg(){
return this;
}
}
public class Fruit extends Produce {
package private Fruit(){};
Fruit isFruit(){
return this;
}
}
ADDITIONAL
@LouisWasserman
Firstly the number of sub types of Produce is limited by making its ctor package private. By including 2 isXXX methods, im stating a fact there are only 2 sub classes ever, which is nicer than doing instanceof checks. Maybe its just me but, this approach also means there are no casts in other code or the above, which has to be a good thing right ?
Also isnt returning an empty list from a method when a search or query fails kind of the same as returning null to mark that the operation isFruit() failed when attempting to cast a Veg to a Fruit ?
I found a quick example in GWT in JType which is a clone of the Eclipse JDT i believe. Anyway that origin doesnt matter but here we have two very well konwn products doing exactly what im describing...
There are plenty of other isXXX that try and cast or return null, ive pasted a few below.
/**
* Returns this instance as a {@link JAnnotationType} if it is an annotation
* or <code>null</code> if it is not.
*/
JAnnotationType isAnnotation();
JArrayType isArray();
JClassType isClass();
JClassType isClassOrInterface();
/**
* Returns this instance if it is an enumeration or <code>null</code> if it is
* not.
*/
JEnumType isEnum();
JGenericType isGenericType();
First of all I think this is a terrible pattern. The super class should generally not be aware of its subclasses.
What if you add another subclass of
Produce
? You will need to remember to modifyProduce
. Error prone.To answer your question though, I would avoid
isFruit
, as users might expect it to return a boolean. If forced to use this pattern, I would probably usegetFruit()
orasFruit()
.