sonar-delphi
sonar-delphi copied to clipboard
Instantiating a bounded array range should always start from 0
Prerequisites
- [X] This rule has not already been suggested.
- [X] This should be a new rule, not an improvement to an existing rule.
- [X] This rule would be generally useful, not specific to my code or setup.
Suggested rule title
Bounded array range should start from 0
Rule description
This rule would pick up on cases when a bounded array variable has a non-zero start when instantiating.
var
Foo: array[1..5] of String; // non-compliant
Bar: array[0..4] of String; // compliant
Rationale
Since RTL list always start from 0 index, there's no good reason for a bounded array range to start from non-zero. To make looping through such as arrays uniform, we should always start from zero.
I think this is some oversimplification - and while often starting with 0 is preferred there are good reasons to start with a value that is not 0, for example, any representation of values for any number range that exists in reality where most things don't start with 0 but with 1. Also, it usually is good practice to use Low and High for looping through such arrays (maybe that should be a rule) and then it does not matter what actual range is being used
I don't think that this rule would go into the default Sonar way quality profile.
The idea has merit though.
It's typically undesirable to have arrays that aren't indexed from 0, and it can be quite confusing when this is the case. After all, any dynamic array or collection type is indexed from 0, and so many developers make the reasonable assumption that any array will start from 0.
Not sure about the suggested title though, I think something more like: Array types should be indexed from zero
Stefan presented the opposite viewpoint of "who cares what the starting index of the array is when Low exists?"
That's an equally valid approach that can be expressed through another (non-default) rule, enforcing the usage of Low and High. I'd be happy to accept a feature request (and/or pull request) for that rule.