Friday, March 4, 2016

Refactoring - pull up method

This refactoring is applied when two classes have an identical method. It can be moved up to the parent.

Let's continue the example from previous post:

class BankAccount {
    var balance : Float = 0
}

class CheckingAccount: BankAccount {
    func displayAlert(){
        if balance < 0 {
            print("You have a negative balance of \(balance).")
        }
    }
}

class SavingAccount: BankAccount {
    func displayAlert(){
        if balance < 0 {
            print("You have a negative balance of \(balance).")
        }
    }
}

We have just refactored the balance field, but we noticed we also have a method (displayAlert) that is identical. We can apply the same refactoring and move it up the hierarchy.

class BankAccount {
    var balance: Float = 0
    
    func displayAlert(){
        if balance < 0 {
            print("You have a negative balance of \(balance).")
        }
    }
}

class CheckingAccount: BankAccount {
}

class SavingAccount: BankAccount {
}



No comments:

Post a Comment