When should methods be declared private?

Encapsulation is used to hide certain components of a class from outside the class. We do this by declaring properties and methods as private or protected. Private components can only be accessed from inside your class, protected components can only be accessed from inside your class, and classes that inherit from your class.

So why do we need to declare methods private or protected?

Protecting class state

In imperative programming, we have to worry about different parts of our program unexpectedly changing state. If all class methods were publicly accessible, any interacting class could make any change to the state of your class. If state is unexpectedly changed then your class isn’t being protected from being used in ways you never expected, potentially causing chaos where that class is used.

Protecting class changes

If methods are private, you can change them without worrying about the effects it’ll have elsewhere in the system. Your public methods are your gateway into your class. It’s dangerous to change these methods when any outside code could be relying on it to work the way it currently works. However, private methods can be altered if required since the only calling methods are in the same class.

Testing

Finally, thinking about the methods that will need to be used to interact with your class gives us an idea of what to test in the class. If all methods were public, we’d have to test every method like it was going to be used in many different ways. If we only declare the gateways into our classes as public then we can test the behaviour of our private methods through this interface, and understand the limitations of the class’s behaviour.

You should be careful however, if you’re finding you need to make a lot of private methods in your class, chances are the scope of your class is expanding. You should consider extracting methods with different responsibilities into new classes.

Leave a Reply

Your email address will not be published. Required fields are marked *