Monday, February 22, 2016

Refactoring - hide function

Just like human beings, the classes have some public and some private "parts". And as we know very well, the private business is better to stay private.

As a rule, it is good to make everything private to start with and only make something public if really needed.

Let's consider the following class:


class Account {
    func generateStatement() {
        generateStatementHeader()
        generateStatementBody()
        generateStatementFooter()
    }

    func generateStatementHeader() {
    //...
    }
    
    func generateStatementBody() {
    //...
    }
    
    func generateStatementFooter() {
    //...
    }
}

Among other functionality, the class has a function to generate a statement. This function is calling other three ones for generating the header, body and footer.

In this context, the functions generating parts of the statement should not be accessible from outside, so we can make them private:

class Account {
    func generateStatement() {
        generateStatementHeader()
        generateStatementBody()
        generateStatementFooter()
    }

    private func generateStatementHeader() {
    //...
    }
    
    private func generateStatementBody() {
    //...
    }
    
    private func generateStatementFooter() {
    //...
    }
}

This reduces the risk that another class is accessing this methods and simplify the life of other developers that are inspecting the public API of the class without looking at the code.

No comments:

Post a Comment