This question: The best way to return a status flag and a message from a method in Java is similar to mine, however I would do it in PHP and not in Java (which may have a slight difference here).
Problem:
There is a method that can have either a successful result (it can be more successful) or a “problematic” one. The latter means that the operation failed, but it is also important to know why. Imagine an authentication class method:
public function login($name, $password) { if (successful_authentication) { report success } else { report failure, explain why (eg wrong name/pass, user banned) } }
It would be trivial to return true and false for success and failure, but how to report the cause of the failure?
Possible solutions:
- Return true or false and write another method (getStatus ()) to get a specific problem: for me this is a bit inconvenient.
- Use exceptions: since it is not exceptional for the user to be blocked (an exception would be if the user died when he typed as another author on this site), using exceptions here in these cases would be incorrect (however, the method may generate database exception if the request does not work)
Returns true on success and the line fails with an error code indicating a problem: with PHP it is possible to have nice clean blocks as follows:
$loginStatus = $auth->login('name', 'pass'); if ($loginStatus === true) { doSomething(); } else { if ($loginStatus == 'wrong_login_data') ... elseif ($loginStatus == 'banned') ...
Returns an object of general state (s): a very elegant solution, as well as a reliable future (no problem, if the number of statuses changes or additional data is added later), perhaps the best one:
$loginStatus = $auth->login('name', 'pass') if ($loginStatus->isSuccess) ... else echo $errorMessages[$loginStatus->errorCode];
Any of the two above, but not with a simple string, but with class constants:
$loginStatus = $auth->login('name', 'pass') if ($loginStatus->isSuccess) ... elseif ($loginStatus->errorCode == Auth::ERR_USER_BANNED) ...
With this, it would not be necessary to explain the error codes in the documentation and would be more “natural” (at least for me).
Question:
What would you use (from the above or any other solution)? What has been proven in the long run to be a good way?
Thank you in advance!
php state return-value status
Piedone
source share