Thursday, May 7, 2020

Java: Return enum instead of boolean

We have a game where you place down buildings. So there is always a method that looks like that:

public boolean validPlace(BuildingType type, Location location) {

    for (int ix = 0; ix < type.w; ix++) {
        for (int iy = 0; iy < type.h; iy++) {
            
            if (/* check if overlapping */) {
                return false;
            } else if (/* check if road missing */) {
                return false;
            }
        }
    }
    return true;
}

The problem: While writing the game logic everything is fine, but then comes the UI. A can palce / cannot place is not enough for a good UI, you need the reason. And you usually have another method that finds out the reason. But can we use the same method?

First we need an enum with all the possible problems:

public enum PlacementValidity {
    Ok,
    Overlapping,
    RoadMissing;

    public boolean ok() {
        return this == Ok;
    }
}

Then we just return the enum instead of the boolean:

public PlacementValidity validPlace(BuildingType type, Location location) {

    for (int ix = 0; ix < type.w; ix++) {
        for (int iy = 0; iy < type.h; iy++) {
                
            if (/* check if overlapping */) {
                return PlacementValidity.Overlapping;
            } else if (/* check if road missing */) {
                return PlacementValidity.RoadMissing;
            }
        }
    }
    return PlacementValidity.Ok;
}

The helper function ok() method can also be used to reduce verbosity on the game logic side of the code.

if (validPlace(/* ... */).ok()) {




done_