Replacing “if”s with your own number system

Posted by Michael Williamson on Simple Talk See other posts from Simple Talk or by Michael Williamson
Published on Fri, 14 Sep 2012 08:22:57 +0000 Indexed on 2012/09/14 9:42 UTC
Read the original article Hit count: 780

Filed under:

During our second code retreat at Red Gate, the restriction for one of the sessions was disallowing the use of if statements. That includes other constructs that have the same effect, such as switch statements or loops that will only be executed zero or one times. The idea is to encourage use of polymorphism instead, and see just how far it can be used to get rid of “if”s.

The main place where people struggled to get rid of numbers from their implementation of Conway’s Game of Life was the piece of code that decides whether a cell is live or dead in the next generation. For instance, for a cell that’s currently live, the code might look something like this:

if (numberOfNeighbours == 2 || numberOfNeighbours == 3) {
    return CellState.LIVE;
} else {
    return CellState.DEAD;
}

The problem is that we need to change behaviour depending on the number of neighbours each cell has, but polymorphism only allows us to switch behaviour based on the type of a value. It follows that the solution is to make different numbers have different types:

public interface IConwayNumber {
    IConwayNumber Increment();
    CellState LiveCellNextGeneration();
}

public class Zero : IConwayNumber {
    public IConwayNumber Increment() {
        return new One();
    }

    public CellState LiveCellNextGeneration() {
        return CellState.DEAD;
    }
}


public class One : IConwayNumber {
    public IConwayNumber Increment() {
        return new Two();
    }

    public CellState LiveCellNextGeneration() {
        return CellState.LIVE;
    }
}


public class Two : IConwayNumber {
    public IConwayNumber Increment() {
        return new ThreeOrMore();
    }

    public CellState LiveCellNextGeneration() {
        return CellState.LIVE;
    }
}


public class ThreeOrMore : IConwayNumber {
    public IConwayNumber Increment() {
        return this;
    }

    public CellState LiveCellNextGeneration() {
        return CellState.DEAD;
    }
}

In the code that counts the number of neighbours, we use our new number system by starting with Zero and incrementing when we find a neighbour. To choose the next state of the cell, rather than inspecting the number of neighbours, we ask the number of neighbours for the next state directly:

return numberOfNeighbours.LiveCellNextGeneration();

And now we have no “if”s! If C# had double-dispatch, or if we used the visitor pattern, we could move the logic for choosing the next cell out of the number classes, which might feel a bit more natural. I suspect that reimplementing the natural numbers is still going to feel about the same amount of crazy though.

© Simple Talk or respective owner

Related posts about Uncategorized