csharpsquid:S109 - magic numbers in validation attributes

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.

Hi @KrylixZA

Thanks for the report. I confirm this is a recurring pain and we want to improve it.

We have S109 - reduce false positives · Issue #4737 · SonarSource/sonar-dotnet · GitHub opened to improve this rule, and this usecase is documented in the issue.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.