One of the side effect of using a method out of a library (for which you do not have source code) is that you are not pretty sure if it changes state of a related object. And if it did, when you are least expecting them to, you might have more headaches than you could imagine. But what if the creator of library had struck with the CQS Principle ?
Command Query Separation
CQS, or Command Query Separation was introduced by Bertnard Meyer and it states that every method should be either a command that performs an action, or a query that returns data to the caller, but not both.
Or in other words, Bertnard Meyer wants us to separate our methods into two broad categories, Commands and Queries. Commands can change observable states of the object (and hence has a side effect), but doesn’t return a value. On other hand, Queries does not change states of the object and returns a value. It doesn’t have a side effect and can be called any number of times without having any implication.
The advantage of adhering to the CQS Principle is that the Client have a clear understanding of which methods would be causing a side-effect on the object state and which doesn’t.
// Queries PersonInfo GetUserDetails(int userId); // Command void UpdateUserName(int userId, string userName);
However, it is not always possible to follow the CQS Principle. There are times when you would want to modify the state and return an object as well. The most noticeable example is when you work with Stacks. Consider the following code.
Stack sampleStack = new Stack(); sampleStack.Push("DummyDataString"); var fromStack = Test.Pop();<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>
As you can see from the code above, the Pop Method of Stack Object not only returns a value, but modifies the state of Object as well. The same applies to Queue as well. Likewise, there might be scenarios in our code wherein we would like to do both state change as well as return value with a method. Hence, CQS is a good principle to follow whenever possible, but one needs to be aware that there could be exceptions.