Tuesday 20 October 2020

Commands, queries and side-effects (object interface design)

Commands and queries

"A machine has 2 types of buttons, command and query buttons. When a command button is pressed, the machine performs work and its state is modified. When a query button is pressed, the machine returns some information about it." - Bertrand Meyer

Command corresponds to procedures, they do not return any results. For example:

class MyMachine {

public:

    void SetName(const char * name); // is a command/procedu

}

Query corresponds to functions or attributes, for example:

class MyMachine {

public:

    void SetName(const char * name);     // command/procedure

    const char * GetName() const;        // query/function        

    bool ProcessingReady() const;        // query/attribute

private:

    const char * name;

}


Side effects

 "A side effect on an object is an operation that may change at least one attribute of the object."

The above command and query view is important with relation to side effects since  according to Bertrand Meyer in his book XXX (Chapter 7.7.2 "Commands and queries", Page 134)...

"The clean seperation between procedures and functions averts many of the pitfalls of traditional programming. Side-effect-producing functions, which have been elevated by some langauges (C seems to be the most extreme example) to the status of an institution, conflict with the classical notion of function in mathematics. A mathematical function will always give the same result when applied to the same argument."

Conclusion

From this information, we can create better class interfaces and keep them "more true" to the mathmatical foundation of abstract data type theory. This means that our code is closer to "formal verification" than guesswork.



No comments:

Post a Comment

The difference between class and object.

 The difference between class and object is subtle and misunderstood frequently. It is important to understand the difference in order to wr...