HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMajor

Checking for a condition, even if it's always true

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conditionalwayscheckingtrueforeven

Problem

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 ' '

Solution

Don't use a comment. Use code. Specifically, assert builder.length() >= 2 and assert builder.charAt(builder.length() -2) == ' '. Assertions will clearly indicate the preconditions, and they can be excluded by the compiler or jvm so they don't impact the deployed code.

Context

StackExchange Code Review Q#110398, answer score: 21

Revisions (0)

No revisions yet.