3

I'm creating a UI table component that returns an array of selected indices.

Some typical return values would be

var myRetVal1 = [0];//one value selected 
var myRetVal2 = [0,1,2,3,8,11];//multiple value selected

as you can see I'm always returning an array.

I had an idea to return -1 when nothing is selected, but then I thought that might be confusing when in every other condition an array is returned.

So checking for an empty set of values would be either

//returns -1
var selectedItems = tbl.GetSelectedIndex();
if(selectedItems !== -1){
   //we have data to process
}

OR

//returns []
var selectedItems = tbl.GetSelectedIndex();
if(selectedItems.length > 0){
   //we have data to process
}

OR

//returns null
var selectedItems = tbl.GetSelectedIndex();
if(selectedItems){
   //we have data to process
}

Maybe I'm making too big a deal over this, but is there a standard expectation for this type of control?

As I build other controls should they conform to a standard empty return value or should they always return a "empty" version of their expected return type?

Brandon Boone
  • 283
  • 2
  • 7

2 Answers2

6

I would return an empty array. It bothers me when people return null collections instead of empty collections. The majority of what I would be doing with your return value will be iterating over it, mapping over it etc. and my functions will work correctly with an empty array, but will either break, or have to be modified to deal with null

The worst is when somebody writes a function that returns null for no elements, just the element for 1 element, and an array of elements for multiple elements. It can triple the size and complexity of my code just because I have to check for all the different conditions (I don't mind complex code, but I do mind unnecessarily complex code).

WuHoUnited
  • 1,400
  • 1
  • 9
  • 13
5

I'd be okay with either of the latter. I don't like the first one because you're changing the actual data type returned (int rather than array).

Optimally, I'd go with the second one as it makes more semantic sense. If you're returning an array of selected items, then it makes more sense (again, semantically) to check array.length === 0 than array === null.

Demian Brecht
  • 17,555
  • 1
  • 47
  • 81