Command Query Separation: A Technique for Reducing Code Complexity
One helpful way to reduce the complexity of your code is to be intentional about how and where your code produces side effects.
Useful code must do at least one of two things:
- Produce a side effect
- Return data
Simple code should do one or the other.
What is Command Query Separation?
In his book, Code That Fits In Your Head, Mark Seemann offers the following advice:
Don't return data from methods with side effects, and don't cause side effects from methods that return data. If you follow that rule, you can distinguish between these two types of [procedures] without having to read the implementation code.
This is known as Command Query Separation (CQS).
What are "Commands"?
A "command" is a procedure that produces a side effect but does not return a value. While there are exceptions, VBA Sub
routines generally fall into this category.
What are "Queries"?
In this context, a "query" is a function that returns data but does not produce a side effect. Importantly, this is a separate concept from that of a database query.
What are Pure Functions?
A query can be either deterministic or non-deterministic. Deterministic queries are known as pure functions and have several desirable qualities:
- They are easy to test.
- They readily compose. As Seemann puts it, "If the output of one function fits as the input for another, you can sequentially compose them. Always."
- "You can replace a pure function call with its result," Seemann continues. "The function call is equal to the output. The only difference between the result and the function call is the time it takes to get it."
"[Pure functions] collapse arbitrary complexity to a single result; a single chunk that fits in your brain."
Related reading
Cover image created with Microsoft Designer