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.
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.
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;
}
}
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;
}
}