Issue - Private fields only used as local variables in methods should become local variables

Must-share information:

  • which versions are you using
    SonarQube 6.2

  • what are you trying to achieve
    Sonar Qube is raising a Major issue with code that I think it shouldn’t and it seems to be inconsistent. I have attached screen shot to show the issue. The language is C#. The screen shot shows the code where the issue is raised and that Sonar Qube is inconsistent with one of the private variables even though it is used exactly the same way as the others. We use depedency injection to inject the dependencies into private variables which are assigned in constructor and used in the methods. I don’t understand why (a) SonarQube thinks its a code smell and (b) why is it inconsistent to reporting this event though the private variables that it reports are used exactly the way that the ones that aren’t being reported.

Here’s sample code where we get this Issue

 public class XYZ: ApiController

    {

 
// We GET THE ISSUE WITH THIS VARIABLE
        private readonly IApplicantMarketingPreferecesService marketingPreferecesService;

 
  
        public MarketingPreferenceController(IApplicantMarketingPreferecesService marketingPreferecesService)

        {

            this.marketingPreferecesService = marketingPreferecesService;
 
        }

 
 
        [HttpGet]
 
        public async Task<IHttpActionResult> GetApplicantMarkeingPreferenceById(Guid applicantId)

        {
 
            var applicants = await marketingPreferecesService.GetApplicantMarkeingPreferenceById(applicantId);

 
            return Ok(applicants);
 
        }


        [HttpPost]
 
        public async Task<IHttpActionResult> SaveApplicantMarkeingPreference(ApplicantMarketingPreferencesRequest saveApplicantRequest)
  
 
        {
  
 
            var applicant = await marketingPreferecesService.SaveApplicantMarkeingPreference(saveApplicantRequest);

 
            return Ok(applicant);

 
        }


         [HttpPost]  
  
        public async Task<IHttpActionResult> DeleteApplicantMarketingPreference(Guid caseApplicantId)

        {


            var applicants = await marketingPreferecesService.DeleteAllCaseApplicantMarketingPreferenceByCaseApplicantId(caseApplicantId);


            return Ok(applicants);

 
        }


 
    }

Here’s a screenshot where SonarQube is inconsistent is raising this issue. You’ll see that private variable mappingService doesn’t get flagged up even though its used exactly the same way as the others.

Hi @znajeeb,

Thanks for the feedback. We are aware that the current implementation of this rule has a lot of problem and we are currently working on a rewrite of the rule which should stop raising those FPs.

Thank you,
Amaury