Command–query separation principle [re: @mustuse as a function attribute]
mw
mingwu at gmail.com
Wed Oct 19 06:27:46 UTC 2022
On Wednesday, 19 October 2022 at 05:41:19 UTC, mw wrote:
> DbC is a seemingly simple concept, but actually it's deeper
> than you often thought, it affects many details of language
> design.
OK, an informal exercise: derive command query separation
principle from DbC.
The contract in DbC mostly exhibits as assertions in the code.
The programmer can insert assertions at any place of the code,
without changing the code's original semantics (i.e the behavior
when the assertions are turned-off, e.g. in release mode). In an
OOP language, most of the time the assertions are checking some
properties of an object, hence any method that can be called in
an assertion must be a query (i.e a query can be called on an
object for any number times without changing that object's
internal state). So now we have query method.
But we do need to change an object's state in imperative
programming, then those methods are classified as commands. After
changing an object state, the command must NOT return any value.
Why? because otherwise, the programmer may accidentally want to
call that command and check the returned value in some assertions
... then you know what happens in the end: the program behaves
differently when assertions are turn on in debug mode and off in
release mode.
Therefore, we have this:
"""
every method should either be a command that performs an action,
or a query that returns data to the caller, but not both.
"""
More information about the Digitalmars-d
mailing list