Answer the question
In order to leave comments, you need to log in
Is it good: a function returns multiple data types?
I am writing a function that will return either an array or null (if the array is empty).
Is it good practice? Or is it better to make it always return only an array?
Thank you!
Answer the question
In order to leave comments, you need to log in
An empty array is also data, which is no different from an array with elements. It just has 0 elements.
If your array is being used as a collection of elements of the same type, then I would use an empty array, even if there are no entries.
If the array is a certain structure, then I would return null if the element is not found, or the same array if found
. For example, getting one string from the base.
Will return null if no element exists
Disgusting.
After calling such a function, you will have to check the type and perform various actions.
Either return an empty array, or throw an exception.
or null (if the array is empty).
If an array is expected, then an array must be returned. No other types, it is better not to return, so as not to do additional checks.
What interface do you make like this and it will be, null is the absence of data, if the php language can be returned and nullable even with strict typing, and it’s difficult to talk about design, since it can be an array, but in fact a map, which is better described by an object, and then null will be justified
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question