Details
SonarQube version: 9.1 community edition
Scanning method: Azure DevOps pipelines
Language: C#
Problem
I am currently facing an issue where the SonarQube rule about magic numbers for C# is blocking pull requests from being merged over validation attributes.
The magic number rule is an obvious one that is a must as it helps us keep our code maintainable in the long run. The only problem is when I have a DTO model and I want to apply constraints to certain properties, it complains saying that I should create constants for this. My problem with using constants for validation attributes is it now introduces one further click to see what the validation rules are which I don’t necessarily feel is the right way to go about it.
Example
Non-compliant:
public class Person
{
[StringLength(200)] // complains here.
public string Name { get; set; }
[StringLength(100)] // complains here.
public string Surname { get; set; }
}
Compliant:
Personally, I feel this is worse:
public class
{
private const int NameLength = 200;
private const int SurnameLength = 100;
[StringLength(NameLength)]
public string Name { get; set; }
[StringLength(SurnameLength)]
public string Surname { get; set; }
}
The example above is trivial but if you have a large project with multiple models and a separate class called Constants
that has all these, you either have to mouse over or navigate to the constants to actually see what the validation is.