Search code examples
javainterfaceinstanceof

Casting and instance of or nearly empty interface?


I'm programming some kind of board game containing robots, items and such.

At one point, I need to get the energy value of a robot or an item that can have energy. The way this is programmed is that each robot and each item having energy have an EnergyContainer class as a field (to prevent code redundancy) and an energy Value class.

Now, basically, I call a method evaluate() that receives an Element. Element is an abstract class which robot and items extend. Not all elements have energycontainers. If possible, I need to call the getEnergyContainer on this element, but only if it is an element that has it of course.

I can think of a couple solutions: using a lot of instanceOf and then casting. So asking for example, if the element is instanceof robot, cast element to robot and call getEnergyContainer on the element. This has as clear disadvantage that I need to do this for every energy having subclass of element.

Second solution is defining an interface containing only a getEnergyContainer method and make all energy having classes implement this. The only purpose for this interface is then to facilitate the one method and it would be nearly empty.

Unless anybody has a better idea, what is the "best" solution? Nearly empty interfaces are used as Marker interfaces I think, but this it is one and only purpose so I'm a bit inclined against it.


Solution

  • If possible, I need to call the getEnergyContainer on this element, but only if it is an element that has it of course.

    Why would you not want to call it on an element that doesn't have an energy container? If it doesn't have an energy container, either return a reference to some "null object" implementation of EnergyContainer, or return a null reference. It depends on what you want to do with it later - if you can easily implement some sort of "neutral" energy container, then the null object pattern is the simplest approach. Otherwise, just:

    EnergyContainer container = element.getEnergyContainer();
    if (container != null) {
        // Use the container
    }
    

    There are no doubt those who would argue that this is in some senses "impure" - but it's almost certainly simpler than most alternatives.