M
M
Michael2018-02-05 17:16:55
PHP
Michael, 2018-02-05 17:16:55

What should be returned: null or false?

How many have already written different functions, but did not understand what needs to be returned in different situations. For example, I have a ProductRepository. In the save method I have to return true or false or throw an exception - that's understandable. The delete method will do the same. And in the find method, I have to return the answer or not found. Is "not found" an exception and if not, what should I return: null or false? And if I want to read data from a file, then if it is empty, what should I return, null? It may be necessary to look at it depending on the situation. I would like to understand once and for all what to do in such situations. Tell me in a nutshell.
UPD:
I looked at how it's done in Symfony.

/**
 * ...
 * 
 * @return object|null
 */
public function findOneBy(array $criteria, array $orderBy = null)
{
}

/**
 * ...
 *
 * @return array
 */
public function findAll()
{
}

It can be seen that if 1 record is not found, then it will be null, and in find, whatever it is, there will be an array.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Fedorov, 2018-02-05
@qonand

in such situations, it is worth returning null or Null-object , depending on how your code reacts to the situation when nothing is found. Throwing an exception in such situations is not particularly appropriate, after all, “not found” is not an exceptional situation, but quite a common one ... returning false is also somehow not a camelfo (if there is false, it should be true)

L
Lazy @BojackHorseman PHP, 2018-02-05
Tag

nothing changes. if the method returns an array, then in the absence of a result, an empty array must be returned

A
Antonio Solo, 2018-02-05
@solotony

and I think that it is completely indifferent what to return. the main thing is to write the specification and comply with it. and of course, within the framework of one project, it is probably necessary to observe a single style.
you can also return a "response" object that contains the result - success/failure, response data, error code
about exceptions - exceptions are a way to "pretty" crash.

N
novrm, 2018-02-06
@novrm

Strange, of course, but...
Repository methods must return an entity or null, or an array of entities, or an empty array.
On that it and repositories.
What you write true, false or null should return services that are an intermediary between repositories and controllers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question