Posts Find versus get functions
Post
Cancel

Find versus get functions

Oftentimes find* and get* functions, such as findByEmail or getByEmail functions are used interchangeably. There is however a subtle difference in expectation, even with the words find and get.

Using find implies that a search is done, but there is doubt whether a result exists. When using get something has prompted the assumption that a result must exist.

When using find in a function name, the function must be able to return null.

1
2
3
4
public function findByEmail(string $email): ?User
{
    return $this->executeQuery($email);
}

When using get in a function name, if the result is not found an exception must be thrown.

1
2
3
4
5
6
7
8
9
public function getByEmail(string $email): User
{
    $user = $this->executeQuery($email);
    if ($user === null) {
        throw InvalidUser::notFound($email);
    }
    
    return $user;
}

When using either get or find does not matter for the flow of the code, you should use the get version to have the code be more explicit.

This post is licensed under CC BY 4.0 by the author.