Wednesday, March 2, 2016

Refactoring - Pull up constructor body

As a rule of thumb, each time you see the same code in different places, look for ways to remove the duplication.

This refactoring applies when two or more subclasses have similar code in the init method. We can move that code in the superclass.

Have a look at the following example:

class Vehicle {
    var make: String?
    var model: String?
    var mileage: Float?
    var maximumSpeed: Float?
    var horsePower: Float?
    var colour: UIColor?
    
    init() {
        //...
    }
}

class Car: Vehicle {
    var numberOfDoors: Int?

    init(make: String, model: String, mileage: Float, maximumSpeed: Float, horsePower: Float, colour: UIColor, numberOfDoors: Int) {
        super.init()
        self.make = make
        self.model = model
        self.mileage = mileage
        self.maximumSpeed = maximumSpeed
        self.horsePower = horsePower
        self.colour = colour
        self.numberOfDoors = numberOfDoors
    }
}

class Motorcicle: Vehicle {
    var numberOfWheels: Int?

    init(make: String, model: String, mileage: Float, maximumSpeed: Float, horsePower: Float, colour: UIColor, numberOfWheels: Int) {
        super.init()
        self.make = make
        self.model = model
        self.mileage = mileage
        self.maximumSpeed = maximumSpeed
        self.horsePower = horsePower
        self.colour = colour        
        self.numberOfWheels = numberOfWheels
    }
}

I marked with bold the duplicated code. To apply this refactoring, we move the common code into the superclass, removing a good few lines of code:

class Vehicle {
    var make: String?
    var model: String?
    var mileage: Float?
    var maximumSpeed: Float?
    var horsePower: Float?
    var colour: UIColor?
    
    init(make: String, model: String, mileage: Float, maximumSpeed: Float, horsePower: Float, colour: UIColor) {
        self.make = make
        self.model = model
        self.mileage = mileage
        self.maximumSpeed = maximumSpeed
        self.horsePower = horsePower
        self.colour = colour
    }
}

class Car: Vehicle {
    var numberOfDoors: Int?
    
    init(make: String, model: String, mileage: Float, maximumSpeed: Float, horsePower: Float, colour: UIColor, numberOfDoors: Int) {

        super.init(make: make, model: model, mileage: mileage, maximumSpeed: maximumSpeed, horsePower: horsePower, colour: colour)

        self.numberOfDoors = numberOfDoors
    }
}

class Motorcicle: Vehicle {
    var numberOfWheels: Int?
    
    init(make: String, model: String, mileage: Float, maximumSpeed: Float, horsePower: Float, colour: UIColor, numberOfWheels: Int) {

        super.init(make: make, model: model, mileage: mileage, maximumSpeed: maximumSpeed, horsePower: horsePower, colour: colour)        
        self.numberOfWheels = numberOfWheels
    }
}



No comments:

Post a Comment

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