laravelunit-testingsonarqubesonarqube-scan

Define a constant instead of duplicating this literal "required" 5 times


I have connected my laravel project with sonar coverage. I got duplicated line errors in contollers. I want to know how do I fix them.

Define a constant instead of duplicating this literal "required" 5 times.

Define a constant instead of duplicating this literal "street_line_1" 4 times.

Define a constant instead of duplicating this literal "token" 6 times.

enter image description here

enter image description here


Solution

  • Let's take a look at the error and why sonar is recommending this

    Define a constant instead of duplicating this literal "required" 5 times

    This means that sonar wants you to avoid repeating the string literal "required" multiple times in your code, and instead define a constant in one place and reuse this constant wherever you need the literal.

    So it's recommending something like this

    class ValidationRules
    {
        public const REQUIRED = 'required';
    }
    
    
    $request->validate([
        'field' => [ValidationRules::REQUIRED]
    ]);
    

    So why is sonar suggesting us to change it like this?

    Well, the goal is mainly for better static analysis, IDE support and makes updating it easier. If you have such constants, most modern IDE's should be able to do a lot of magic with this. For example, phpstorm and vscode ( may require an extension) can find all references of this constant, and allow you to update it at once.

    If it was just a string literal instead of constant, your IDE will have no clue what it is or what it's supposed to do. You would need to perform refactoring manually ( A find and replace could help, but it may end up replacing something which you weren't intending, so needs thorough review )

    So if you find yourself repeating string literal, should try to refactor it to reduce repetition.

    It might seem tedious, you're right, it is tedious and the benefits it brings may never be useful, but it keeps your code cleaner.

    Now that we've got the proper solution out of the way, here are some "hacks" incase you find making constants not worth the effort.