The Only Principle To Follow To Write Reusable Code

Rafael A. George Duval
2 min readJan 31, 2024

--

It’s essential to ensure that methods have a single responsibility, making them easy to change and reuse.

This involves asking questions about their job and summarizing their duties in a single sentence. It’s also recommended to hide data from oneself to protect the code from unexpected changes. Data often have behavior that may not yet be known, so it’s best to send messages to access variables instead of thinking of them as data; it’s best to keep this knowledge in one place.

The design becomes clearer by refactoring a class so that each method has only one responsibility.

Methods must have a single responsibility, like classes because it makes them easy to reuse and change. Small methods help to improve the design by making it easier to rearrange behavior. The consequences of change should be evident in the changing code and in distant code that relies upon it.

The cost of any change should be proportional to the benefits the difference achieves. Existing code should be usable in new and unexpected contexts. The code itself should encourage those who change it to perpetuate these qualities.

Having each method serve a single purpose makes what the class does more evident.

Methods with a single responsibility offer several benefits, such as exposing hidden qualities, avoiding the need for outdated comments, encouraging reuse, and being easy to move to another class when design changes occur.

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