I have a C++ struct and a method:
struct Account
{
unsigned int id;
string username;
...
};
Account GetAccountById(unsigned int id) const { }
I can return an Account struct if the account exists, but what to do if there’s no account?
I thought of having:
- An “is valid” flag on the struct (so an empty one can be returned, with that set to false)
- An additional “is valid” pointer (const string &id, int *is_ok) that’s set if the output is valid
- Returning an Account* instead, and returning either a pointer to a struct, or NULL if it doesn’t exist?
Is there a best way of doing this?
You forgot the most obvious one, in C++:
Return
trueand fill in the provided reference if the account exists, else returnfalse.It might also be convenient to use the fact that pointers can be null, and having:
That could be defined to return
trueif the account id exists, but only (of course) to fill in the provided account if the pointer is non-null. Sometimes it’s handy to be able to test for existance, and this saves having to have a dedicated method for only that purpose.It’s a matter of taste what you prefer having.