Monday, February 29, 2016

Refactoring - parameterize method

When you have similar methods that are doing the same thing with the exception of a value, create one common method and pass the value.

Let's consider the following (ugly) class for a product:

class Product {
    var price: Float = 0
    
    func increasePriceBy5Percent() {
        price = price * 1.05
    }

    func increasePriceBy10Percent() {
        price = price * 1.1
    }

    func decreasePriceBy5Percent() {
        price = price * 0.95
    }
    
    func decreasePriceBy10Percent() {
        price = price * 0.9
    }
}

Let's take a test product and apply the methods:

let product = Product()
product.price = 100

product.increasePriceBy10Percent()
product.increasePriceBy5Percent()
product.decreasePriceBy10Percent()
product.decreasePriceBy5Percent()

We observe that the methods perform the same actions with the exception of the percentage value.

We can easily create just one method and receive the percentage as a parameter:

class Product {
    var price: Float = 0
       
    func applyPercentage(percentage:Float) {
        price = price * (1 + percentage)
    }
}

Our method calls become now:

product.applyPercentage(0.1)
product.applyPercentage(0.05)
product.applyPercentage(-0.1)
product.applyPercentage(-0.05)

Not only the code is cleaner, but it allows us more freedom. For example we can now apply an increase of 20%.

No comments:

Post a Comment

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