1 Simple Rule to Encapsulate Code in Ruby

Rafael A. George Duval
2 min readJan 19, 2024

--

To better encapsulate an object, hide data access behind methods and limit external access to the object’s internal state.

It’s important to avoid asking objects for information and perform a function for them. Instead, we should command objects to do what they need to do. Each object is responsible for its part of the domain and should tell the next object what to do. Encapsulation should remove the ability to add if statements, forcing us to use commands instead of queries. This prevents us from putting processing in the wrong place.

Start each class definition with private methods to identify if the object is doing too much.

The object that owns the data can decide what should be displayed and not how. A value object is intended to be queried, and only that you don’t do anything else with it. It simplifies our parameters. You can look at your code and see the direction of information, and if things are traveling west, that’s a sign that you’re leaking information. Information leaks responsibilities.

Commands encourage polymorphism.

They push responsibility down into objects. It is a loosening coupling. To encapsulate data, always return self from command methods. If you’re returning self and hiding information about an object so that you cannot query it, then there’s no other option. Encapsulation refers to grouping data with the methods that manipulate that data.

Encapsulation conceals an object’s information, represented by its data or internal state.

[¹]: Practical Object-Oriented Design: An Agile Primer Using Ruby

--

--

Rafael A. George Duval
Rafael A. George Duval

Written by Rafael A. George Duval

✍🏼 Building a Solo Digital Media Company 🧪 Snippets of Text [https://snippetsoftext.substack.com/subscribe]

No responses yet