Query Functions, Command Functions and Pure Functions
Posted in Software on November 23rd, 2009 by Jan Willem Tulp – Be the first to commentLast week 2 colleagues of mine and myself gave a Scala workshop at Logica. One of the participants was asking whether getDate was a function or not. His question led to an email discussion today about what functions are, and how they relate to the Command Query Seperation (CQS) principle. The definitions coined in Eric Evans book about Domain Driven Design were helpful in defining the definitions.
After several exchanging several emails, we finally came to the following definitions:
- Query Functions: functions that retrieve information about the system. They are not pure functions, because applying these kinds of functions to its arguments may result in different values. GetDate() would be a Query Function, because everytime it is applied, a different value is returned.
- Command Functions: functions that alter the state of the system. They should not return a value (void in Java, or Unit in Scala). setName(String name) in Java would be example of a Command Function. Command functions therefore have side-effects.
- Pure Functions: functions that always return the exact same value for the exact same input. These are mathematical functions and don’t have side-effects. In Scala the following function is a Pure Function: def inc(x: Int) : Int = x + 1. For the input 4, this function will always return 5, no matter how many times you invoke it, and it doesn’t change the state of the system.
What’s your opinion about these definitions?





