如何重新设计代码以解决 SonarQube "Getters and setters should access the expected fields" 错误?
How to redesign code to reslove SonarQube "Getters and setters should access the expected fields" bug?
示例代码:
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
集合在基础 class 中定义并在 PropertyGrid
中使用。实际代码要复杂得多 - 还有其他 class 派生自 Bar
并使用 Properties
(数百个属性)。
SonarQube 在 Property1
和 Property2
的吸气剂和 setter 中发现了错误:
Getters and setters should access the expected fields
我可以抑制或禁用 SonarQube 的规则,但上面的代码很容易出错 - 如果开发人员 copy/paste 编码,它可能会以类似以下的形式结束:
public double Property3
{
get => (double)Properties[Property3Name];
set => Properties[Property2Name] = value;
}
寻找上述错误并非易事。
关于如何重新设计代码以修复 SonarQube 的警告并降低代码出错率的任何想法?
您应该避免使用魔术字符串,而应使用 nameof
public int Property2 {
get => (int)Properties[nameof(Property2)];
set => Properties[nameof(Property2)] = value;
}
示例代码:
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
集合在基础 class 中定义并在 PropertyGrid
中使用。实际代码要复杂得多 - 还有其他 class 派生自 Bar
并使用 Properties
(数百个属性)。
SonarQube 在 Property1
和 Property2
的吸气剂和 setter 中发现了错误:
Getters and setters should access the expected fields
我可以抑制或禁用 SonarQube 的规则,但上面的代码很容易出错 - 如果开发人员 copy/paste 编码,它可能会以类似以下的形式结束:
public double Property3
{
get => (double)Properties[Property3Name];
set => Properties[Property2Name] = value;
}
寻找上述错误并非易事。
关于如何重新设计代码以修复 SonarQube 的警告并降低代码出错率的任何想法?
您应该避免使用魔术字符串,而应使用 nameof
public int Property2 {
get => (int)Properties[nameof(Property2)];
set => Properties[nameof(Property2)] = value;
}