Tuesday, March 15, 2016

Replace subclasses with fields

The subclasses need to have a reason for existence. A very good reason.

When that reason disappears or becomes slim, it might be time for removing the subclass.

Let's consider the following hierarchy of classes:

class Account {
    func isChecking() -> Bool {
        return false
    }
}

class CheckingAccount: Account {
    override func isChecking() -> Bool {
        return true
    }
}

class SavingAccount: Account {
    override func isChecking() -> Bool {
        return false
    }
}

While at the beginning the CheckingAccount and SavingAccount were different in functionality, in time, the only difference between them remained just the isChecking method that returns true for one and false for another.

We can refactor this structure, by adding one property to the Account class to reflect if the account is checking or not.

class Account {
    var isCheckingAccount: Bool = false
    func isChecking() -> Bool {
        return isCheckingAccount
    }
}



No comments:

Post a Comment

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