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.

\$\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;  
    }
}
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.