How to avoid instanceof operator in this case

design-patterns, java, oop, polymorphism

Solution

Okay, here's another approach you can take.

 public class Cell {

     private int x;
     private int y;
     private OccupationInfo occupationInfo;

     public int posX() {
         return x;
     }

     public int posY() {
        return y;
     }

     public OccupationInfo getOccupationInfo() {
        return occupationInfo;
     }

     public boolean isFree() {
        return occupationInfo == null;
     }
  }

And then...

  public class OccupationInfo {
      private Player owningPlayer;
      // any other data you would've put in `TakenCell`
  }

This may or may not be good for your exact purposes but it's a clean and simple design.

Problem

I'm writing simple game with cells which can be in two states Free and Taken by player. ``` interface Cell { int posX(); int posY(); } abstract class BaseCell implements Cell { private int x; private int y; public int posX() { return x; } public int posY() { return y; } ... } class FreeCell extends BaseCell { } class TakenCell extends BaseCell { private Player owningPlayer public Player owner() { return owningPlayer; } } ``` In each turn I need to inspect all cells to calculate next cell state with method as below ``` // method in class Cell public Cell nextState(...) {...} ``` and collect (in `Set`) all cells that are not yet taken. The method above returns `Cell` because cell may change from Free to Taken or the opposite. I'm doing something like below to collect them: ``` for (Cell cell : cells) { Cell next = cell.futureState(...); if(next instanceof FreeCell) { freeCells.add(currentCell); } ... } ``` It's ugly. How to do that to avoid such instanceof hacks? I'm not talking about another hack, but would like to find out proper OOP solution.

Original source