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

This site utilizes Google Analytics, Google AdSense, as well as participates in affiliate partnerships with various companies including Amazon. Please view the privacy policy for more details.

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:


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;

Leave a Reply

Note that comments won't appear until approved.