Why should an API return 'void'?

前端 未结 7 1225
南方客
南方客 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: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).

提交回复
热议问题