Why should an API return 'void'?

前端 未结 7 1220
南方客
南方客 2021-02-07 00:23

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

相关标签:
7条回答
  • 2021-02-07 00:41

    Besides the design reasons, there is also a slight performance cost (both in speed and space) for returning this.

    0 讨论(0)
  • 2021-02-07 00:42

    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.

    0 讨论(0)
  • 2021-02-07 00:48

    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.

    0 讨论(0)
  • 2021-02-07 00:57

    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.

    0 讨论(0)
  • 2021-02-07 00:58

    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).

    0 讨论(0)
  • 2021-02-07 00:58

    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.

    0 讨论(0)
提交回复
热议问题