Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding the "Non-constant fields should not be visible" code analysis warning

I have an object that has a list of business rules that are checked when the object is validated.

At the top of the class I create static fields of type BusinessRule as shown below:-

public class SyncFile : Waterstons.Patterns.Entities.BaseEntity<Guid>
{        
    public static BusinessRule NameRequiredRule = new BusinessRule("Name", "The audit file must have a name");
    ....


    protected override void Validate()
    {
        if (Id == default(Guid))
        {
            AddBrokenRule(IdRequiredRule);
        }
        ....

This leads to code analysis complaining that I shouldn't have public fields unless they are const. I'm not sure I can define them as const however based on how I'm using them.

So is there a better way to approach this? Should I expose them as properties as below instead?

    public static BusinessRule _nameRequiredRule = new BusinessRule("Name", "The audit file must have a name");
    public static BusinessRule Test
    {
        get { return _nameRequiredRule; }
    }

Or is there a better way to approach this?

like image 261
Ross Dargan Avatar asked May 11 '26 02:05

Ross Dargan


1 Answers

You can change your static field declaration to this

 public static readonly BusinessRule NameRequiredRule = new BusinessRule("Name", "The audit file must have a name");

So to make sure public field won't change during execution. Note also to make BusinessRule class immutable, so that not only reference can't be changed in NameRequiredRule but also instance contents can't be changed during runtime.

If you can't enforce immutability - consider declaring NameRequiredRule static field as private and create a static property.

private static BusinessRule _nameRequiredRule = new BusinessRule("Name", "The audit file must have a name");
public static BusinessRule NameRequiredRule
{
    get { return _nameRequiredRule; }
}
like image 118
Ilya Ivanov Avatar answered May 12 '26 15:05

Ilya Ivanov