Prefer two-element enum types to boolean parameters

By , last updated January 28, 2016

How many times we write a program like this:

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. So we do this:

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

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

This was a fast 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 how we should have done it:

public enum Sex {MALE, FEMALE}

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

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

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>

*