Prefer two-element enum types to boolean parameters

By , last updated October 6, 2017

When we start writing a program, we don’t always know how it will look like in the future. So we start simple and create a procedure to calculate something for a person:

public void doSmth() {
    Salary s = calculateSalary(Person p);
    ...
}

private Salary calculateSalary(Person p) {
   return 100;
}

And then we need to change it in order to have different salaries for males and females. A quick solution is to add a boolean gender that will differentiate a male from a female.

Here is a simple example of a Java code with boolean gender:

public void doSmth() {
    Salary male = calculateSalary(Person p, true);
    Salary female = calculateSalary(Person p, false);
    ...
}

private Salary calculateSalary(Person p, boolean gender) {
   if(gender) return 100;
   else return 50;
}

This was a fast and dirty fix. But what happens if we need to have more options later? What do these true/false mean?

Using ENUM types in Java makes your code easier to read, especially if you are using an IDE that supports autocomplition. Also, it makes it easy to add more options later.

Here is an example of a clean Java code with an enum type:

public enum Gender {MALE, FEMALE}

public void doSmth() {
    Salary male = calculateSalary(Person p, Gender.MALE);
    Salary female = calculateSalary(Person p, Gender.FEMALE);
    ...
}

private Salary calculateSalary(Person p, Gender gender) {
   if(gender.equals(Gender.MALE) return 100;
   else return 50;
}

We should have created a two-element ENUM type with two options: MALE and FEMALE. Because now it will be much easier to expand it to the third gender!

Always prefer Enum types to boolean parameters in Java!

Senior Software Engineer developing all kinds of stuff.

Comments

Be the first to comment.

Leave a Reply


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*