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?
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With