Encapsulation & Private Methods
The concept of Object-oriented programming (OOP) is intriguing and allows us to model a program around objects and their interactions rather than solely through data and logic.
Encapsulation is a pattern for capturing an object’s intention and only exposing the components needed to interact with it. The above code allows the outside to call #walk on the Person object. Through the #walk method, the object will move its legs. However, we cannot tell the Person to move its legs. It knows how to walk by itself; the logic is there.
From outside the class, I should only know that I can tell the object to walk and not how to walk (unless we wanted to control a person like that). We don’t want the outside to be able to modify how person moves their legs as that may have detrimental effects on our Person object and can have us worrying needlessly about it.
Get Robert Lin’s stories in your inbox
Join Medium for free to get updates from this writer.
Another example would be a clock. The clock can show me the current time and can have its time set (public methods). The logic of how the clock actually works is encapsulated inside the clock object. The complexity of the gears and motors is better left hidden to the outside user.
Think of encapsulation as a black box that you don’t want users to look into, because they shouldn’t care how something is done so long as the result produced is what they want.
Private Methods! — Example: Vending Machine
Encapsulation is important to us as it separates details of a class that are irrelevant from the functions that matter. It effectively creates a barrier around an object such that code is contained. If something is poorly encapsulated, we have to worry about how a change in code might affect our system as a whole. An encapsulated method cannot be accessed outside of the object; the only way to modify it is through the object itself.
This increases the abstraction of an object by simplifying the complexities and focusing on what an object does in comparison to real life. When we look at a vending machine we can expect that we can feed it money, punch some buttons and get our food. We can then proceed to tackle a problem without thinking too much about the inside logic or the how.






