In my program there is the following piece of code where I must delete a ' '
from the second to last index in a StringBuilder
:
builder.deleteCharAt(builder.length() - 2);
I do not surround it with checks to either condition builder.length() >= 2
or builder.charAt(builder.length() - 2) == ' ')
, because I am 100% sure that both these conditions will always be true, even though at first glance, it is not so obvious.
I'm torn between feeling that just because I have a higher understanding of the code, doesn't mean I should neglect the conditions for the sake of others in the team. But at the same time, if I do check for these conditions, it would be absolutely unnecessary.
My solution is to simply add a comment, but I was wondering if is this considered to be good practice?
builder.deleteCharAt(builder.length() - 2); // should always be ' '
assert
is a great way to handle this problem as stated below. \$\endgroup\$String
"A.M."
becomes["A", ".", "M", "."]
. After processing the first three tokens, theStringBuilder
holds the stringA . M
and the current token is"."
. Based on certain flags I've set, I determine I've come across an acronym. So here is where I callbuilder.deleteCharAt(builder.length() - 2);
to delete the second to last character in theStringBuilder
. \$\endgroup\$