Friday, February 12, 2016

Refactoring - encapsulate downcast

Consider the following class hierarchy:

class Car {
    //....
}

class ElectricCar : Car {
    //...
}

We have a small database of cars:

var cars = [Car(), Car(), ElectricCar(), ElectricCar(), Car()]

And one function that is returning one electric car:

func findElectricCar() -> Car? {
    for car in cars {
        if car is ElectricCar {
            return car
        }
    }
    return nil
}

In our code, in multiple places we have to downcast the objects from Car to ElectricCar:

var electricCar1, electricCar2, electricCar3: ElectricCar

electricCar1 = findElectricCar() as! ElectricCar
electricCar2 = findElectricCar() as! ElectricCar
electricCar3 = findElectricCar() as! ElectricCar

This, of course, is useless as we know already findElectricCar is returning an Electric car.

To improve the code, we need to move the casting directly into the function

func findElectricCar() -> ElectricCar? {
    for car in cars {
        if car is ElectricCar {
            return (car as! ElectricCar)
        }
    }
    return nil
}

Now our code looks more elegant:

var electricCar1, electricCar2, electricCar3: ElectricCar

electricCar1 = findElectricCar()
electricCar2 = findElectricCar()
electricCar3 = findElectricCar() 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.