Marc Andreson
Marc Andreson

Reputation: 3495

RTTI vs. additional methods

Some of my classes should be treated differently. Which solution is better:

  1. Introduce new interface to my class hierarchy and check whether the class implements it or not, using RTTI (runtime time identification)
  2. Add a method which returns boolean value that indicates whether this class should be treated normally or deserves special treatment

The following examples illustrates the above situations:

1.

interface SpecialTreatment {}

class Base {}    

class Special extends Base implements SpecialTreatment {}

class Normal extends Base {}


Base reference = new Special();
if(reference instanceof SpecialTreatment)
    // do something special
else
    // normal class

2.

interface Treatment {
    boolean special();
}

class Base {}

class Special extends Base implements Treatment {
    boolean special() { return true; }
}

class Normal extends Base implements Treatment {
    boolean special() { return false; }
}

Treatment reference = new Special();
if(reference.special() == true)
    // do something special
else
    // normal class

Upvotes: 2

Views: 209

Answers (1)

Adrian Regan
Adrian Regan

Reputation: 2250

If the 'reason' for treating the class differently is a design decision then mark it as so via an interface signature as in solution 1.

If there is a chance that some state in your application would govern this, then use solution 2.

And example of this, is the java.io.Serializable interface with no methods or fields that is used to identify implementations that are serializable. You decide at design time whether the object was serializable.

A note on the performance of instanceof, after additional comment.

You could also look at using Annotations as an alternative...

-- EDIT AFTER TAKING COMMENTS ON BOARD ---

If you really want to not go down the instanceof (which is very fast) or annotations you could do this..

interface Special {
    bool isSpecial();
}

abstract class RuntimeSpecial implements Special {
    protected abstract bool _determineSpecial();

    public isSpecial() { return _determineSpecial(); }

}

class IsSpecial implements Special {
    public isSpecial() { return true; }
}

class IsNotSpecial implements Special {
    public isSpecial() { return false; }
}

Now extend whatever is appropriate....

Upvotes: 1

Related Questions