All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S1118.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Whenever there are portions of code that are duplicated and do not depend on the state of their container class, they can be centralized inside a "utility class". A utility class is a class that only has static members, hence it should not be instantiated.

How to fix it

To prevent the class from being instantiated, you should define a non-public constructor. This will prevent the compiler from implicitly generating a public parameterless constructor.

Alternatively, adding the static keyword as class modifier will also prevent it from being instantiated.

Code examples

Noncompliant code example

public class StringUtils // Noncompliant: implicit public constructor
{
  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

or

public class StringUtils // Noncompliant: explicit public constructor
{
  public StringUtils()
  {
  }

  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

Compliant solution

public static class StringUtils // Compliant: the class is static
{
  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}

or

public class StringUtils // Compliant: the constructor is not public
{
  private StringUtils()
  {
  }

  public static string Concatenate(string s1, string s2)
  {
    return s1 + s2;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy