When Can Using If/Else Be Considered Unfavorable in Object Oriented Programming?



Occasionally I may include affiliate links, which means I may get a commision if you purchase something via that link. Check out my privacy policy for more info.

This is my answer to this question on Quora.

One way using if/else would be bad design, from and OOP standpoint, is if you’re using a chain of instanceof checks instead of polymorphism.

For instance:

if(myObject instanceof Object1) {
  // do the thing
} else if(myObject instanceof Object2) {
  // do the thing
} else if(myObject instanceof Object3) {
 // do the thing
}

Instead, you could have a doTheThing method for each of the three object types:

myObject.doTheThing();

Of course, that means each of those objects would have to inherit (and possibly override) doTheThing from some sort of SuperObject.

However, if you’re comparing values, it’s not necessarily a bad design. Grades would be an example:

if(score >= 90) {
  grade = A;
} else if(score >= 80) {
  grade = B;
} else if(score >= 70) {
  grade = C;
} else if(score >= 60) {
  grade = D;
} else {
  grade = F;
}