Frage

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?

War es hilfreich?

Lösung

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
}else{
//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.

Andere Tipps

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

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

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top