Why should an API return 'void'?

前端 未结 7 1222
南方客
南方客 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题