5

Possible Duplicate:
When and why you should use void (instead of i.e. bool/int)

What is the reasoning behind making all functions (and methods!) return a uniform type, usually int, as a status?

To me it feels odd; especially when you're calling a getter and it returns a status (which is usually the same always) and sets one of the parameters to the value you're getting.

Plumenator
  • 205
  • 1
  • 7

2 Answers2

3

If there is no chance of failure there is no sense in returning a status. This makes only sense, if the code that uses the function would actually evaluate the returned status code and respond to it with some error message or some way to correct an error. Too many useless status codes and programmers using it will form a habit of ignoring them.

Though depending on the actual functionality it may be relevant to keep that option for changes you may want to make in a future version of some library. (But then you should know what you are doing)

It can be questioned if the status code approach is a good idea anyway. I prefer exceptions for error handling, since they make the code more readable.

In some languages (and many use cases) you need the return value for other purposes. Either to simply return the result of a function or to return something like this as you do when overloading certain operators in C++. So making it a principle to return a status wont work anyway.

thorsten müller
  • 12,058
  • 4
  • 49
  • 54
  • If I had a dollar for every junior programmer who thought they were engineering correctly by checking for something that should never be false in runtime code, and exiting out of the function with an error code... almost always useless, typically not handled anyway, and makes the code more complex and less readable. Just put assertions in, and if you seriously can't stop one or more of them tripping in the final weeks of testing, add some patch logic, thereby acknowledging that you don't fully understand how your own program works. – Kaitain Oct 24 '21 at 01:03
2

They usually write that kind of interface for binary compatibility reasons, where you can't just throw an exception and you need to leave yourself room for increasing the range of errors.

DeadMG
  • 36,794
  • 8
  • 70
  • 139
  • 1
    Returning status when it makes sense is great. But is it a good idea to make it a coding standard to make your methods always return an error code? That way, you'd just end up discarding the return values most of the time (coz they don't mean anything) and ignore the crucial ones too. – Plumenator Aug 06 '11 at 09:51
  • Increasing the range of errors may cause behavioral incompatibility though. – fejd Aug 06 '11 at 10:11
  • 1
    @Plumenator: No, it's not a great idea. It's a terrible idea. It is, however, binary compatible, unlike it's alternatives. – DeadMG Aug 06 '11 at 11:04