When writing an API or reusable object, is there any technical reason why all method calls that return \'void\' shouldn\'t just return \'this\' (*this in C++)?
For examp
Besides the design reasons, there is also a slight performance cost (both in speed and space) for returning this.
Methods that return void state more clearly that they have side effects. The ones that return the modified result are supposed to have no side effects, including modifying the original input. Making a method return void implies that it changes its input or some other internal state of the API.
Is there a technical reason for following this route?
One of the C++ design guidelines is "don't pay for features you don't use"; returning this
would have some (slight) performance penalty, for a feature which many people (I, for one) wouldn't be inclined to make use of.
I'd imagine one reason might be simplicity. Quite simply, an API should generally be as minimal as possible. It should be clear with every aspect of it, what it is for.
If I see a function that returns void, I know that the return type is not important. Whatever the function does, it doesn't return anything for me to work with.
If a function returns something non-void
, I have to stop and wonder why. What is this object that might be returned? Why is it returned? Can I assume that this
is always returned, or will it sometimes be null? Or an entirely different object? And so on.
In a third-party API, I'd prefer if that kind of questions just never arise.
If the function doesn't need to return anything, it shouldn't return anything.
If you had Reverse()
return a string
, then it wouldn't be obvious to a user of the API whether it returned a new string or the same-one, reversed in-place.
string my_string = "hello";
string your_string = my_string.reverse(); // is my_string reversed or not?
That is why, for instance, in Python, list.sort() returns None
; it distinguishes the in-place sort from sorted(my_list).
The technical principal that many others have mentioned (that void
emphasizes the fact the function has a side-effect) is known as Command-Query Separation.
While there are pros and cons to this principle, e.g., (subjectively) clearer intent vs. more concise API, the most important part is to be consistent.