Conditional method blocking

I have an application in which the parent has a method for performing validations, and each child overrides the method to perform additional checks. Sort of:

class Parent { virtual void DoValidations (Delegate addErrorMessage) { //do some validations } } class Child : Parent { override void DoValidations (Delegate addErrorMessage) { base.DoValidations(addErrorMessage); //the parent method is always called //do some extra validations } } 

I added a new IsDisabled property which, when true, will not perform any checks.

 class Parent { boolean IsDisabled; virtual void DoValidations (Delegate addErrorMessage) { if (IsDisabled) return; //do some validations } } 

I also want that for each child, if the IsDisabled property is true, additional checks are not performed. What is the best template to use here?

+6
source share
2 answers

I would share this functionality with a separate method:

 private void DoValidations(Delegate addErrorMessage) { if (!this.IsDisabled) { this.OnDoValidations(addErrorMessage); } } virtual void OnDoValidations(Delegate addErrorMessage) { } 

Now OnDoValidations can be redefined as desired. The IsDisabled check will be performed inside the base class.

+6
source

Well, this is due to SOLID 'L' (Liskou Substitution Principle). I suggest you use the following approach:

1) Create an interface, for example:

 public IValidator { void Validate(Delegate addErrorMessage); } 

2) Create an abstract base class with the abstract DoValidations () method:

 public abstract class BaseValidator : IValidator { public void Validate(Delegate addErrorMessage) { DoValidations(addErrorMessage); } protected abstract DoValidations(Delegate addErrorMessage); } 

3) Inherit the parent from BaseValidator (or make the parent element a base class instead of BaseValidator):

 public class Parent: ValidatorBase { public override void DoValidations(Delegate addErrorMessage) { // do validation } } 

4) Inherit the child from the parent:

 public class Child : Parent { public override void DoValidations(Delegate addErrorMessage) { // do validation } } 

5) Now it's time to add the IsDisabled property. We just need to change ValidatorBase and IValidator:

 public interface IValidator { bool IsDisabled {get; set; } void Validate(Delegate addErrorMessage); } public abstract class BaseValidator : IValidator { public bool IsDisabled { get; set; } public void Validate(Delegate addErrorMessage) { if(!IsDisabled) { DoValidations(addErrorMessage); } } protected abstract DoValidations(Delegate addErrorMessage); } 

6) Now use your validator IValidator = _factory.Create ():

 validator.IsDisabled = false; validator.Validate(); 

Good luck

0
source

All Articles