Command and Query Methods in Object-Oriented Programming

Rafael A. George Duval
1 min readFeb 10, 2024

--

In programming, there are two types of methods: command and query.

Command methods do not return values, but they cause side effects that change the system somehow. These side effects can happen in the same or a different component. Command methods travel to the right.

Query methods, on the other hand, return values but do not change the system in any way. Query methods travel to the left. When you call a query method, you handle the value it returns.

If you want to access data within an object, you can use a query method. But the object must ensure that you don’t cause any issues.

The provider of the object must enforce the values between the query method call and return.

To better encapsulate an object, you should hide data access behind methods and limit external access to the object’s 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