Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(start, end) vs. (start, length) in API design

I've seen two alternative conventions used when specifying a range of indexes, e.g.

subString(int startIndex, int length);

vs.

subString(int startIndex, int endIndex);

They are obviously equivalent in terms of what you can do with them, the only difference being whether you specify the ending index or the length of the range.

I'm assuming that in all cases startIndex would be inclusive, and endIndex exclusive.

Are there any compelling reasons to prefer one over the other when defining an API?

like image 495
mikera Avatar asked Jan 11 '13 05:01

mikera


2 Answers

Someone should do a study of typical call sites to find out which approach yields more succinct code (and therefore probably correct code).

I like the argument that using 'length' you don't have to look at the documentation, but you may already be looking at the documentation to determine whether the 2nd integer is the 'end' or the 'length'. If you name it endExclusive, then it's just as self-documenting.

like image 50
George Forman Avatar answered Sep 21 '22 11:09

George Forman


I'd prefer the length one simply because it gives me one less question to ask/look up in the documentation.

For the endIndex based one - is that an inclusive or exclusive end point?

(For either variant, the same question could be asked about startIndex, but it would be a perverse API that makes it exclusive).

like image 28
Damien_The_Unbeliever Avatar answered Sep 20 '22 11:09

Damien_The_Unbeliever