Thursday, May 7th, 2020 code enum java techniques • 271w
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_
Thursday, July 26th, 2018 code enum java techniques • 263w

The is always that tip that floats around that you should always use enums instead of booleans, even when there is only two values.

Of course the point is that it will be much easier to read and mainly to extend in the future.

So from a simple

 public void setVisible(boolean value) { ...

you go to

 public enum Visibility { Visible, Gone }

 public void setVisible(Visibility value) { ...

And in the future you could add eg. the Invisible value.

But you miss the simplicity of a boolean and you also get the verbosity of an enum

 setVisible(Visibility.Visible)

and this happens

 setVisible(value ? Visibility.Visible : Visibility.Gone)

The classic solution is to add methods like show() or hide() to avoid the use of the enum

However a simply solution to collect the benefits of both world:

 public void setVisible(boolean value) {
     setVisible(value ? Visibility.Visible : Visibility.Gone)
 }

 public void setVisible(Visibility value) { ...

where the two boolean values will correspond to the two most used values of the enum

And why not add and some methods for the most used values

 public void show() {
     setVisible(Visibility.Visible)
 }

So in the end you have everything

 show()
 setVisible(true)
 setVisible(Visibility.Visible)


done_