jeudi 29 décembre 2016

Refactoring a function that returns different data types

I'm not sure what the most efficient way of doing this would be but I believe it's good practice to have a function that returns one data type, whether it be a boolean or string but in some situations I can see how difficult it would be to implement such a strict rule, for example the code below will return an object if a database record is found otherwise it will return false.

public function get()
{
   $record = $this->db->query('select id, first_name, last_name from users where id = :id', ['id' => 1]);

   if ($record) {
      return new User($record['id'], $record['first_name'], $record['last_name']);
   } else {
      return false;
   }
}

My question is what is the recommended best practice in this situation?

Aucun commentaire:

Enregistrer un commentaire