简体   繁体   中英

Empty interface or expose a private validation

I have a base abstract class that calls a private validation method in constructor. For part of its descendants I want to skip this check. This class have too many usages and I can't move the validation from the base class.

Which is better solution

  • create an empty interface, implemented in classes that will skip this check
  • expose this property and make it protected virtual and override it with empty body in derived classes that should skip the check

(any other better solutions will be also appreciated)

If this consideration applies only to this class, the 2nd approach I'd choose. If it will be the case in more classes, therefore it would represent some behaviour independent of class, I would go with 1st option (then also you can make use of polymorphism in cases, where you want to use just classes without check).

public abstract class BaseClass {
    public BaseClass(bool? validate = true) {
        if (validate.HasValue && validate.Value) {
            Validate();
        }
    }

    private void Validate() { }
}

public class ChildClass1 : BaseClass {
    public ChildClass1() : base() { }
}

public class ChildClass2 : BaseClass {
    public ChildClass2() : base(false) { }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM