Friday, September 12, 2014

Transform if else (conditional) with polymorphism

Switch and consecutive if-else statements are not necessary anti-patterns, but you should consider using polymorphism in this situations, especially  if conditional is complex and long.
Sometimes when you refactor your code in this way, you actually learn something new about your data and make your code easier to follow.
Polymorphism also give you advantage when you have same conditional in through your code on several places and for example you want to introduce new branching, which in case of polymorphism will be just new type.

Let see it in example:
public class ConditionalPolymorphism {
    
    //smelly approach
    public int carSpeed(String car) {
        if ("Hyundai".equals(car)) {
            return 180;
        } else if ("Mazda".equals(car)) {
            return 160;
        } else if ("Nissan".equals(car)) {
            return 190;
        } else {
            throw new InvalidParameterException(
                    "Parameter not legal: " + car);
        }
    }

    //polymorphic approach
    public int carSpeed(Car car) {
        return car.speed();
    }

    public static void main(String[] args) {
        ConditionalPolymorphism conditionalPolymorphism = 
                new ConditionalPolymorphism();
        System.out.println(
                conditionalPolymorphism.carSpeed("Hyundai"));
        System.out.println(
                conditionalPolymorphism.carSpeed(new Hyundai()));
    }
}

interface Car {
    int speed();
}

class Hyundai implements Car {

    public int speed() {
        return 180;
    }
}

class Mazda implements Car {

    public int speed() {
        return 160;
    }
}

class Nissan implements Car {

    public int speed() {
        return 190;
    }
}
This is pretty simple and naive example, but you can see basic mechanics behind it. Polymorphic code is more elegant and it is written more in object-oriented manner. Also in this example you can omit parameter check, which will further reduce code complexity.

No comments:

Post a Comment