Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, should I use getters or interface tagging for constant properties?

Suppose I am modelling different animals in Java. Every animal has some combination of these abilities: walk, swim and fly. For the example, the ability set is constant.

I can store this information as getters that return constants. For example:

public class Penguin implements Animal {

    public boolean canWalk() {
        return true;
    }

    public boolean canSwim() {
        return true;
    }

    public boolean canFly() {
        return false;
    }

    // implementation... 
}

The run-time check is then:

if (animal.canFly()) {

    // Fly! 
}

Or I can use "tagging" interfaces:

public class Penguin implements Animal, Flyer, Swimmer {

    // implementation... 
}

The run-time check is then:

if (animal instanceof Flyer) {

    // Fly! 
}

What are the advantages and disadvantages of each approach?

like image 481
sdgfsdh Avatar asked Oct 13 '15 08:10

sdgfsdh


1 Answers

Marker interfaces are a bit of an anti-pattern in modern Java, required in earlier times because of no way to directly add metadata to a class. The "modern" approach is annotations:

@Retention(RetentionPolicy.RUNTIME)
@interface Flyer {
}

@Retention(RetentionPolicy.RUNTIME)
@interface Swimmer {
}

@Flyer @Swimmer
public class Penguin implements Animal {
}

And the runtime check:

if(Animal.class.isAnnotationPresent(Flyer.class)) {
    // fly!
}

You can use this approach if all you want to know is if an Animal has this trait, that is flight and swimming capability is pure metadata.

What are you trying to achieve? I wouldn't call this OOP, because the OOP approach is usually not to query capabilities and execute object-specific conditional logic, it is to use polymorphism.

like image 98
sh0rug0ru Avatar answered Nov 01 '22 17:11

sh0rug0ru