views:

198

answers:

3

I have a few functions that should return an array, to have it merged with another array.

However, sometimes there's nothing to return. What's the best scenario here?

  1. Return an empty array and merge that with the full one OR
  2. Return null, store the return in a variable, check that variable and THEN merge it if needed.

I'm asking this because sometimes the shortest route isn't the fastest, and I don't really know what array_merge() does under the hood.

+1  A: 

If there is nothing to return, return just an empty array. It sounds most logically.

Balon
+1  A: 

I'd go for...

  1. Return an empty array if nothing went wrong

  2. Return false (or throw an exception) if an error occurred

...as whilst this will mean that you have to do a bit of extra work, it's probably better practice and will pay dividends in the long run. (array_merging with the return value might look neat, but it's a bit dubious unless there's no possibility of any errors occurring.)

middaparka
+1  A: 

Return the empty array. Compare the complexity of your two options

  1. Return an empty array and merge that with the full one OR
  2. Return null, store the return in a variable, check that variable and THEN merge it if needed.

When you write a function, people other than you are going to use it (this includes the you from 6 month forward who has no idea what current you is doing). If you return null, someone using your function needs to know it might not return an array, so anytime they use your function then need to wrap their variables in a lot of is_array or is_set checks. This leads to harder to maintain code down the road, or bugs where it works when your app/system works when an array is returned, but not when a null is returned. If your function always returns an array, people can safely pass it to functions expecting an array. (this is why some advocates of strong type enforcement hate PHP. In a language like Java this doesn't happy because functions have return a specific type of thing)

You attention to performance is laudable, but in general the built in array manipulation functions are pretty well tuned, and are only going to bottleneck a small percentage of the time. In day to day code running, the performance benefits of checking the value of the variables and merging in a zero element array are going to be negligible.

Go with the cleaner API, benchmark, and then optimize specific cases where you start seeing a performance problem.

Alan Storm
That's a valid point, my future me thanks you!
skerit