Encapsulation in Ruby for Better Code Quality

Rafael A. George Duval
2 min readMar 29, 2024

--

Value Objects are immutable data structures that can’t be altered, which helps simplify the code and reduce errors.

In Ruby, it’s easy to enforce encapsulation by always returning “self” from every method that modifies the state. This ensures that the last statement executed by the method will be the return value in Ruby, improving the clarity and efficiency of your code.

A value object is intended for querying and should not be manipulated in any other way, which simplifies our parameters.

Promote polymorphism and encapsulation, pushing responsibility down into objects, thereby reducing coupling. Value Objects are immutable data structures that cannot be altered. Value Objects are global and language-agnostic, and each language has its way of implementing them.

Value objects are objects whose property values determine their equality.

Using value objects to represent valid cases can cut ambiguity caused by Test-Doubles. Value objects are immutable, and creating invalid objects can cause unexpected issues. Validations can reduce the risk of system crashes due to invalid states, but they are not foolproof.

Value objects merge attributes to remove duplication and enable rich behavior.

Values in your system afford to shift process boundaries. Every value in your system is a potential message between two processes.

[¹]: 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