7
7
700ghz2019-05-30 16:40:10
Software design
700ghz, 2019-05-30 16:40:10

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

7 answer(s)
V
Victor Golovko, 2019-05-30
@siptik

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

O
OnYourLips, 2019-05-30
@OnYourLips

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.

R
Ronald McDonald, 2019-05-30
@Zoominger

or null (if the array is empty).

It is better to return 0 or -1 as an int or error as a string so that the programmer who will use it does not have to write the binding himself.

L
Lone Ice, 2019-05-30
@daemonhk

For all sorts of PSR functions like one data type should return

A
abbrakadabbra, 2019-05-30
@abbrakadabbra

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.

B
bestxp, 2019-06-01
@bestxp

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 question

Ask a Question

731 491 924 answers to any question