Sample code:
public class Foo: Bar
{
protected static readonly string Property1Name = "Property1";
protected static readonly string Property2Name = "Property2";
public string Property1
{
get => (string)Properties[Property1Name];
set => Properties[Property1Name] = value;
}
public int Property2
{
get => (int)Properties[Property2Name];
set => Properties[Property2Name] = value;
}
}
Properties
collection defined in base class and used in PropertyGrid
. Real code much more complex - there are other classes derived from Bar
and use Properties
(hundreds properties).
SonarQube found bugs in getters and setter of Property1
and Property2
:
Getters and setters should access the expected fields
I could suppress or disable SonarQube's rule, but the code above is error-prone - if a developer copy/paste code it could be end up with something like:
public double Property3
{
get => (double)Properties[Property3Name];
set => Properties[Property2Name] = value;
}
Hunting for the above bug is not an easy task.
Any ideas how to redesign code to fix SonarQube's warnings and make the code less error-prone?
You should avoid the magic strings and use nameof
instead
public int Property2 {
get => (int)Properties[nameof(Property2)];
set => Properties[nameof(Property2)] = value;
}