1
\$\begingroup\$

I have a User class that will throw an exception if the userid provided in the parameter does not correspond with a user.

I've written a helper function that will return true or false depending on whether a userid belongs to a user or not, but was wondering if my use of a try {} catch {} to do so is correct:

 private function userExists($userid)
 {
 $user_does_not_exist = false;
 try
 {
 $user = new User($userid);
 }
 catch (Exception $e)
 {
 $user_does_not_exist = true; 
 }
 return $user_does_not_exist;
 }

Any and all critique is greatly appreciated.

asked Jul 12, 2013 at 12:52
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

I would suggest working the other way around. Expect that a user does not exist and only return true if a user is found.

private function UserExists($userId)
{
 $userExists = false;
 try
 {
 $user = new User($userId);
 if($user !== null)
 $userExists = true;
 }
 catch (Exception $e)
 {
 //handle exception
 }
 return $userExists;
}

You can drive this further and ease things by not using a variable to return, like this:

private function UserExists($userId)
{
 try
 {
 return new User($userId) !== null;
 }
 catch (Exception $e)
 {
 return false; 
 }
}
answered Jul 12, 2013 at 13:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.