www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Multiple return type or callback function

reply aberba <karabutaworld gmail.com> writes:
I'm creating a function to authenticate user login. I want to 
determine login failure (Boolean) and error message (will be sent 
to frontend) but D does have multiple return type (IMO could use 
struct but will make code dirty with too much custom types).

struct Result
{
     bool success = false
     string message;
}
Result authen(){}
auto r = authen()
if (r.success) writeln(r.message);



  In such use case, would you use a callback delegates function or 
will use a string (str == "ok", str == "no") or go with a struct?

string authen(){}
string r = authen();
//check if string contains success message to take action.


Or
void authen(void delegate callback(bool success, string message) )
{
     //authenticate
     callback (resultBoolean, message);
}

//use
authen( (success, msg) {
    req.writeBody(msg); // to frontend
});
Jan 23
next sibling parent pineapple <meapineapple gmail.com> writes:
On Monday, 23 January 2017 at 15:15:35 UTC, aberba wrote:
 I'm creating a function to authenticate user login. I want to 
 determine login failure (Boolean) and error message (will be 
 sent to frontend) but D does have multiple return type (IMO 
 could use struct but will make code dirty with too much custom 
 types).

 struct Result
 {
     bool success = false
     string message;
 }
 Result authen(){}
 auto r = authen()
 if (r.success) writeln(r.message);
I use structs like this quite frequently, myself. It works well and I don't think it's particularly ugly. And if you don't want to pollute the namespace with one-off structs, you can also place them inside the function that's returning them (making them voledmort types).
Jan 23
prev sibling parent Basile B. <b2.temp gmx.com> writes:
On Monday, 23 January 2017 at 15:15:35 UTC, aberba wrote:
 I'm creating a function to authenticate user login. I want to 
 determine login failure (Boolean) and error message (will be 
 sent to frontend) but D does have multiple return type
 [...]
Yes, MRV can be done with a tuple auto foo() { import std.typecons; return tuple(true, "123456"); } void main(string[] args) { auto auth = foo; if (auth[0]) auth[1].writeln; } It's more or less like returning a Voldemort struct.
Jan 23