dennisdoomen / CSharpGuidelines

A set of coding guidelines for C# 9.0, design principles and layout rules for improving the overall quality of your code development.
https://www.csharpcodingguidelines.com
Other
745 stars 272 forks source link

Question: AV1008 (avoid static classes) with constants #225

Closed bart-degreed closed 3 years ago

bart-degreed commented 3 years ago

I'm wondering if using a static class that solely contains constants (which are shared between multiple related classes) should be considered an exception to this rule.

For example:

internal static class Keywords
{
    public const string GreaterThan = "greaterThan";
    public const string LessThan = "lessThan";
    public const string StartsWith = "startsWith";
    public const string Equals = "equals";
}

public sealed class NumericComparisonParser
{
    // has internal reference to Keywords.GreaterThan, Keywords.LessThan and Keywords.Equals
}

public sealed class TextSearchParser
{
    // has internal reference to Keywords.StartsWith and Keywords.Equals
}

I consider this preferable over magic strings or duplicating the constants in all types that use them. Or is there a better way to do this I haven't thought of?

dennisdoomen commented 3 years ago

Although I try to keep those constants as close to the most likely source of that set of constants, it is not always possible. Also, when the constants are used in two different modules, I try to be conservative with practicing DRY and just duplicate them. Mapping the constants between the modules then becomes an explicit task of some kind mediator logic.

bart-degreed commented 3 years ago

Makes sense, thanks.