Monday, March 7, 2016

Refactoring - Push down field or method

This refactoring is applied when there is a field or method in a superclass that is used only in one of the subclasses.

One class should have the information it needs to have, so it makes sense to push down that field or method to the subclass where it belongs.

Here is an example:

class BankAccount {
    var overdraft: Float = 0
    
    func enableOverdraft(overdraft: Float){
    }
}

class CheckingAccount: BankAccount {
}

class SavingAccount: BankAccount {
}

BankAccount has the overdraft, but, according to the business rules, an overdraft applies only to a checking account. In this case we can move the functionality to the CheckingAccount class.

class BankAccount {
}

class CheckingAccount: BankAccount {
  var overdraft: Float = 0
    
    func enableOverdraft(overdraft: Float){
    }
}

class SavingAccount: BankAccount {
}

By doing this, not only we move the functionality to the place where it belongs, but we also eliminate the risk to have this functionality called for the incorrect object.

For example, in the first case, the overdraft functionality could have been called for a saving account, which is incorrect.

No comments:

Post a Comment