How to refactor this code OOP code for an interview?

Tag: oop Author: suifeng9858 Date: 2014-04-23

So I was asked to refactor this code in an interview

There is a Shape abstract class. Square, Rectangle which are derived classes of Shape. Square and Rectangle override the method area() of Shape. Now how do I refactor code something like this?

if(object is of type Square) {
    //call area on square
} else if (object is of type Rectangle) {
   //call area of rectangle
} else if(object of type Cube) {
  // call volume of cube

The question was basically how do you avoid multiple if conditions since there can be lot of derived classes and call the appropriate method on that object?

Where does Cube come from? What is its relation with the other types?
Your example is quite vague.
Cube could also derive from Shape. Overriding area to give Volume of the cube.
So is "volume" a different method or is it also the "area" method? Because this could be a simple case of polymorphism: just call area() on whatever shape is passed, you don't have to look at the exact implementation.
Downvoter. Please comment on what you are expecting. I will answer to make it more clear.

Best Answer

Ah now I understand what he wanted to hear was probably that you can add another abstract class, say, AbstractFlatShapes

then check

if (object is instance of AbstractFlatShapes){
//call area
//call volume

to make myself clear

AbstractFlatShapes extends Shape i am quite sure he wanted to hear that. Just imagine there are 15 flat shapes, and you do else if for each shape? to call the same function.


let me wait to see if there are any more answers since this is bit open ended. If not will accept yours as answer.
@user281693 feel free to accept

Other Answer1

Perhaps using a switch—like this example from PHP—would be a good answer?

switch (object) {
    case Square:
        // call area on square
    case Rectangle:
        // call area of rectangle
    case Cube:
        // call volume of cube


I thought the interviewer was expecting something in the lines of Switch statement but I did not know what to answer. I just replied I don't know and we moved to next question.
@user281693 My advice? Interview questions are never right or wrong in what answer you give as long as you can explain the logic to the answer you came up with or—this is key—you know how to question the question even more.
switch and if else are pretty much identical. I mean, i would never refactor something like this, a simple waste of time

Other Answer2

I think the bigger problem with that code is handling two different things in one method: area and volume. So later on in the code it has to check whether the object was a 2-d shape or a 3-d shape yet again since you most likely can't handle area and volume as the same. The shape classes should each implement the methods for whatever purpose it was to get area and volume in the first place