Flagging special conditions on return from a function call

Denis noreply at noserver.lan
Tue Jun 23 04:01:45 UTC 2020


Is there a preferred idiom in D for flagging special conditions 
when returning from a function call? Here "special conditions" 
refers to expected situations (e.g. reaching the end of 
something, like EOF) rather than outright errors (so 
exception-try-catch is inappropriate).

I've come across many ways for a function to return both a value 
and flag, including:

(1) Assign an unused value for the flag (e.g. -1 when the 
function returns an int), and return the combined value/flag.
(2) Return a tuple with the value and the flag
(3) Return a struct or tuple with named value and flag members
(4) Set the function return value normally, and put the flag in 
an "out" variable passed as an argument to the function
(5) Return the flag, and put the value in an "out" variable 
passed to the function (i.e. the reverse of #4)
(6) Use two separate functions, one that returns the value, and 
another that can be called afterwards to check the flag (like 
eof(), for example)
(7) Use a side effect and set a designated global variable

I'm sure there are others.

* Is there a preferred approach?
* Which ones are discouraged?
* General recommendations or guidelines?

If there is a best practice, I'd rather learn it sooner than many 
lines of code later.

(In the interest of brevity, I'll limit my own comments in this 
post to the following: In the past, I've tried to adhere to KISS. 
This means that I would generally prefer #1. But often it isn't 
possible to combine the value and flag that way, in which case 
one of the other methods must be used.)


More information about the Digitalmars-d-learn mailing list