user2871354
user2871354

Reputation: 550

How to avoid null checking - OOP

I am making a game and I have a Tile class that contains an Item.

public clas Tile{
    Item item;
    ....
    public void setItem(Item item){
         this.item = item;
    }

}

When I have a reference to the Tile I want to call the interact() method on the item. How can I do this without checking if the object is null. I don't think the Null Object pattern will work in this scenario because there will be mixed instance cohesion - a subclass of item that would represent an empty item would have an empty interact() method.

Upvotes: 1

Views: 187

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

The stereotypical solution to the mixed instance cohesion problem is to create subclasses (and make sure that the superclass doesn't expose the subclass-specific functionality).

So you create a ItemTile and NonItemTile subclass of Tile.

public abstract class Tile {
    public abstract void interact();
}

public class ItemTile extends Tile {
    private final Item item;
    ....
    public ItemTile(Item item) {
        // Null-check to enforce contract - could be omitted if you make this
        // the responsibility of the caller.
        if (item == null)
           throw new NullPointerException("item");
        this.item = item;
    }

    public void interact() {
        item.interact();
    }
}

Upvotes: 0

Paulo
Paulo

Reputation: 3008

You are trying to find a way to not check if the object is null, when null is an option.

In this case, design to check if item != null, before execute item.interact(), is not an anti-pattern or hacking solution.

Upvotes: 1

Related Questions