Answer the question
In order to leave comments, you need to log in
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()
{
}
Answer the question
In order to leave comments, you need to log in
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)
nothing changes. if the method returns an array, then in the absence of a result, an empty array must be returned
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.
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 questionAsk a Question
731 491 924 answers to any question