DEV Community

Discussion on: Be Careful with String’s Substring Method in Java

Collapse
 
6502 profile image
Andrea Griffini

I'm not questioning your teaching abilities, but that apparently (from tone) you dislike the idea of indexing from 0.

This is unfortunately not uncommon (see the Lua language, for example) but the fact remains that indexing from 1 is a bad idea and EWD was right on this.

Sometimes it helps thinking to indexes as being "between" elements...

content     H   e   l   l   o   ,       W   o   r   l   d   .
          |___|___|___|___|___|___|___|___|___|___|___|___|___|
index     0   1   2   3   4   5   6   7   8   9  10  11  12  13

so the interval 3-5 is clearly "lo" and the number of elements included in the interval a, b is b - a.

This way of thinking simplifies a lot reasoning for example when implementing binary search or raster graphic algorithms.
This mental model is equivalent to [a, b[, but (maybe) easier to understand and remember.

x[i] is just the element between i and i+1.

Some API solve the problem of substring-like interfaces by relying on start/size instead of start/end (this is what Qt does in many cases, for example). Unfortunately the same Qt framework made the wrong choice of using "boundary-inclusive" intervals when implementing right() and bottom() method for integer rectangles, a poor choice that makes hard to write pixel-perfect code and force a lot of +1 and -1 in code: floating point rectangles are ok, and the mistake on the integer case is acknowledged in the documentation (but unfortunately cannot be removed because of backward compatibility reasons).

Thread Thread
 
renegadecoder94 profile image
Jeremy Grifski

What is your end goal here?

Thread Thread
 
6502 profile image
Andrea Griffini

I thought you were asking for comments, so I commented.

I think the view that substring in Java has a "quirk" because uses the [a, b[ convention for intervals is questionable.

That "semi-open interval" is in my opinion the correct approach (may be on par or second only to a start/size approach). A "boundary included" [a, b] would instead be worse for many reasons.

Java has no "quirk" here: it's the correct thing to do (and please note that I'm surely NOT a Java fan, at all).