Wednesday, February 17, 2016

Refactoring - extract subsclass

In some instances, one class is providing functionality for only certain cases.

Assume there is a class to manage a bank account.

The class provides functionality for checking as well as for saving accounts but only the saving accounts bring interest to the owner.

class Account {
    //this function is called only for saving accounts
    func calculateInterest(){
        //....
    }
}

let checkingAccount = Account()
let savingAccount = Account()

Nothing prevents a user for calling checkingAccount.calculateInterest() and also get a result that might not be accurate or in the best case is zero.

The solution to prevent this is to create a sub class and move the specific functionality there:

class Account {
    //some functionality
}

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

let checkingAccount = Account()
let savingAccount = SavingAccount()

In this case, checkingAccount.calculateInterest() would raise a compilation error.

In general, each class should only have the functionality that allows to perform its duties and nothing more.

No comments:

Post a Comment

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