Thursday, July 26, 2018

Java: enum or boolean for two value properties


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_