giovabattelli / roslyn-analyzers

Roslyn Diagnostic Analyzers are customized compiler errors providing real-time feedback to C# developers. Each Analyzer optionally includes an automatic Code Fixer.
MIT License
0 stars 0 forks source link

Avoid variables named '_' #3

Open giovabattelli opened 1 week ago

giovabattelli commented 1 week ago

The following card is not a discard, but a variable named underscore: byte[] _ = ExtractData(reader);

trysherpa[bot] commented 1 week ago

Please note, Sherpa may occasionally provide incomplete or inaccurate information. Always verify critical details and double-check suggested changes before implementation.

Problem Summary

The issue at hand involves avoiding the use of variables named with a single underscore (_). The specific code snippet causing concern is byte[] _ = ExtractData(reader);. The goal is to ensure that variable names are meaningful and adhere to naming conventions, avoiding single-character or non-descriptive names.

Relevant Files

Proposed Changes

Philips.CodeAnalysis.MaintainabilityAnalyzers/Naming/VariableNamingConventionAnalyzer.cs

  1. Update Regular Expressions: Modify the existing regular expressions to explicitly disallow the use of a single underscore as a variable name. The _localRegex and _fieldRegex should be adjusted to exclude _ as a valid name.

    • Example modification:
      private static readonly Regex _localRegex = new(@"^(?!_)([a-z]|[A-Z]).*$", RegexOptions.Singleline | RegexOptions.Compiled, TimeSpan.FromSeconds(1));
      private static readonly Regex _fieldRegex = new(@"^(?!_)(_|\b[A-Z]).*$", RegexOptions.Singleline | RegexOptions.Compiled, TimeSpan.FromSeconds(1));
  2. Enhance AnalyzeVariableDeclaration Method: Ensure that the method checks for variables named _ and reports them as violations. You may need to add a specific condition to handle this case.

    • Example code snippet:
      if (identifier.ValueText == "_")
      {
       Location location = identifier.GetLocation();
       var diagnostic = Diagnostic.Create(Rule, location, identifier.ValueText);
       context.ReportDiagnostic(diagnostic);
       continue;
      }

Summary

To address the issue of avoiding variables named _, the developer should focus on enhancing the VariableNamingConventionAnalyzer to explicitly disallow such names. This involves updating regular expressions to exclude single underscores and ensuring the AnalyzeVariableDeclaration method identifies and reports these as violations. By implementing these changes, the codebase will enforce more meaningful and descriptive variable naming conventions.