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?
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With