Can a boolean be a magic number

Viewed 328

I am wondering how I have to handle with booleans in code.

Let's say I've got a Human class:

   public class Human {

     private final static int NEWBORN = 0;

     private int age;
     private boolean married;

     public Human() {
       age = NEWBORN;
       married = false;
     }

     ...
   } 

Is false in this case a magic number AND should I create a constant like I did with age?

If not, is there any case I have to handle booleans?

1 Answers

Strictly speaking this usage is fine. false is a perfectly self-explanatory value for a boolean named married.

You'll still not see that a lot, because many, many cases that you might naively model with a boolean actually involve a lot more than just two states.

For example, what if you need to handle unmarried, divorced and widowed people differently? Suddenly a simple boolean will not be able to accurately represent your domain data.

When in doubt, you can just introduce an enum (let's say MaritalStatus), even if it starts out with just two values. Adding additional enum values here is easier than changing from a boolean to a different type entirely.

Another common reason to use an enum is because you can add an explicit UNKNOWN value that is surprisingly often needed (and avoids the nasty use of null to indicate "unknown").

Related