-3

Let assume that we have a main() function in which we call a createDirectory() function.
In Python for instance, the code would be:

def main():
    # Do some stuff
    createDirectory(myPath)
    # Do some more stuff

To re-use our created directory, I can see at least two ways:

  • either the createDirectory() function returns 0 in case of success, 1 if it fails to create the directory.
    If the operation succeeds, we know that we can use myPath directly later.
  • or it returns the path to the directory in case of success and None if it fails.

My questions are:

  1. are there any specific names for those two styles: returning a return code (fail, success, etc.) or returning an actual useful value (the path to our created directory in my example)?
  2. Are there any clear benefits choosing one or the other style?
    I usually return meaningful and useful values rather than return codes but I would be interested in knowing why people use the other style.
4
  • 1
    Both styles seem rather poor in Python. Why not raise an exception on failure? Commented Apr 19, 2016 at 12:26
  • I used Python to describe that case just because I wanted to keep the example simple but I would obviously raise an exception in Python for that. My question is rather about the general case. Commented Apr 19, 2016 at 12:58
  • 3
    Then why would you tag Python to the question? It's far from obvious. We're not in your head. The question isn't even answerable in the general case, it entirely depends on the language and the paradigm you're using. Commented Apr 19, 2016 at 12:59
  • I tagged it with Python because it's the language I used to describe the example but I specified "In Python for instance" so I thought people would understand that it's not a Python-specific question. I'm not asking for a fixed answer working in all situations, just some reasons to choose one style over the other. If it depends on the paradigm you use, your answer can be paradigm-specific :) Commented Apr 19, 2016 at 13:20

1 Answer 1

1

Error codes are basically what you use when you really don't have any other choice. Like when using a really low level language where creating new data structures or throwing exceptions is either a bother or taxing on resources.

The same old, same old regarding "program for people, not computers" holds here too. Be as helpful as possible to the developer who is going to get your errors and needs to debug the code that caused them. Error codes are obscure and magic and need to be looked up in docs/memorized. Data structures representing results and exceptions with good types/messages are self-documenting.

The answer really IS unanswerable in the general case though, as was stated in the comments. As always, do what's idiomatic in the language and team you're currently working in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.