Thursday, February 18, 2016

Refactoring - Extract superclass

This refactoring is applied when different classes have similar functionality. In this case, the common code can be move into a new class that becomes the superclass for the other classes.

Consider a checking and a saving account:

class SavingAccount {
    func calculateInterest(){
    }
    
    func createStatement() {
    }
    
    func emailStatement(){
    }
}

class CheckingAccount {
    func calculateFee(){
    }
    
    func createStatement() {
    }
    
    func emailStatement(){
    }
}

While the classes are not identical, we notice some common functionality. 

We'll create another class, Account and extend the current class from it.

class Account {
    func createStatement() {
    }
    
    func emailStatement(){
    }
}

class SavingAccount: Account {
    func calculateInterest(){
    }
}

class CheckingAccount: Account {
    func calculateFee(){
    }
}

This makes the hierarchy more elegant and allows a simpler maintenance. Imagine if the emailStatement functionality needs to be changed, in our second example, we need to change it only in one place.

No comments:

Post a Comment

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