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 usemyPath
directly later. - or it returns the path to the directory in case of success and
None
if it fails.
My questions are:
- 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)?
- 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
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.