I'm writing custom rules for the new rule system in CSLA.NET 4.0 and I'm looking at the rules provided in the CommonRules class in the CSLA source as a guide. I noticed that the property InputProperties declared in the BusinessRule base class has to be initialized in the subclass. Why?
This was a choice I made to avoid overhead. Since most rules are sync, and most sync rules don't need/use input property values like that, creating the collection object for every rule invocation (every rule context) would be a waste.
Also, I rather like using collection initializers to set the values while creating the list object - all in one neat line of code.
I agree that it's unnecessary to initialize the collection for every rule. However, I don't like the fact that a property from a base class throws a NullReference exception if I try to use it, especially for collections. I believe it's more natural and less error-prone to return an empty list. Might I suggest that a better approach would be to lazy-initialize the collection like this:
List<Csla.Core.IPropertyInfo> _inputProperties;
public List<Csla.Core.IPropertyInfo> InputProperties
{
get
{
if (_inputProperties == null)
_inputProperties = new List<Core.IPropertyInfo>();
return _inputProperties;
}
}
The collection is initialized only if it is referenced. Also, the protected setter is not needed. The protected constructor can add the PrimaryProperty to the InputProperties collection if it is called:
protected BusinessRule(Csla.Core.IPropertyInfo primaryProperty)
{
this.InputProperties.Add(primaryProperty);
DefaultSeverity = RuleSeverity.Error;
AffectedProperties = new List<Core.IPropertyInfo>();
PrimaryProperty = primaryProperty;
this.RuleUri = new RuleUri(this, primaryProperty);
}
Just some ideas.
Dave
Copyright (c) Marimer LLC