0

Just a general programming best practices question.

If I have a function like that takes in an array of items and the function then calls a series of other functions which filter and act on the items in the array, should execution continue if at any point we are acting on an empty array? E.g.

arrayItems = [ 1, 2, 3 ]

filtered = filterItems(arrayItems) // Now we have [1,2]
validItems = validate(filtered) // Now we have []
processed = process(validItems) // Acting on []

Should I be checking for an empty array at each step before executing the next function or is it fine to continue if the later functions can handle an empty input?

1
  • 3
    An empty array is perfectly good data -- no need to check for that, until you want to know if it is empty, or, to extract an element.
    – Erik Eidt
    Commented Mar 13, 2019 at 20:41

2 Answers 2

12

Checking against an empty array will increase the size of your code considerably and make it harder to read. The benefit is a tiny improvement in efficiency, but all you save is the price of a few function calls, which are probably insignificant compared to the time it takes to execute those functions even a few times (and you still have to add the cost of the empty() call). Therefore, overall it is much better to leave out the check and just let all your filters do nothing the normal way - by iterating over the empty collection.

1
  • 6
    Yes! While special-casing might not always have a performance-cost/benefit (measure!), the true cost is increased complexity. Commented Mar 13, 2019 at 19:52
6

The question is whether the operation would be meaningful for an empty array.

Take the function count() which returns the number of elements. That is meaningful for an empty array - the count of items would then be 0. So no need to special case the empty array. But take max() which returns the largest value in an array. That is not really meaningful for an empty array. So you will have to check for that.

1
  • Well, the minimum value for the type might make a suitable result for maximum of empty range. Or maybe floating point NaN. Or perhaps that really is an error. Commented Mar 13, 2019 at 22:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.