r/cpp • u/OkEmu7082 • Apr 02 '26
The Command-Query Separation (CQS) principle and its exception
the Command-Query Separation (CQS) principle (Meyer's doctrine) says that a function should be either side effect free or side effect only(no return value). in cpp scientific programming, this makes sense performance-wise since for large objects, it is efficient to allocate once and use function side effect to modify, and one should avoid returning large object that involved the expensive allocation and deep copying.
(modern) fortran's syntax support even makes this principle somewhat explicit, it provides the function(which is usually used without side effect) and subroutine( which is analogues to the c/cpp function that returns void), and in fortran OOP one usually sticks to type bound subroutines instead of type bound functions so that if it is already altering the state of the obj as a side effect there should be no more return values
do you know or come across any exception in cpp scientific programming or in other applications, where the CQS principle should be violated and it is the best way to do it? why?
Edit: how does the usage of functor/lambda in cpp evolve this doctrine
View all comments
1
u/johannes1971 Apr 03 '26
I've never heard of it, and it sounds like fundamentalist BS to me. It would rule out huge numbers of useful design patterns, without any obvious benefit.
For example: fopen? Not allowed: it has side effects (a file gets opened), but it returns a FILE*. How about printf? Not allowed: it has side effects, and returns the number of characters printed. Any function returning an error value: not allowed. Any function that computes a result and caches it, before returning it: not allowed. Any function that makes a change and reports on the subsequent status: not allowed.
About the only way you can deal with that is to have void-returning functions that cause side effects, and then for each one, a second function that is free of side effects just to return the result of the previous function. Is that in any way beneficial? I'm asking because I do see potential new issues. What if I call void_fopen twice in a row, without calling return_fopen_result? So there is a new failure mode, but where is the new benefit of this approach?
Again: I can only see this as fundamentalist nonsense, easily understood as such by anyone who is not in whatever cult is proposing this. It's essentially a religious rule, a ritual that, its priests tell us, is demanded by an invisible higher being, not for our benefit, but for theirs. The game is already given away by the name you gave it: a "doctrine", or in other words: "a belief or set of beliefs held and taught by a Church, political party, or other group".