0

Consider you have the following classes: Class1, Class2 .... Class1000. All the classes are inheriting interface IClass. All the classes can be validated using below code

Validate(IClass class) 
{

}

How can we skip validation for class 200 to class 300 (these numbers can vary, so no logic using numbers) without using if condition?

jsanalytics
  • 13,058
  • 4
  • 22
  • 43
Venkatesan
  • 13
  • 3
  • You need to show what code decides to call `Validate()` and whether `Validate()` could be moved to the class itself. – zaitsman Nov 26 '17 at 22:58

1 Answers1

2

Personally, i'd move your validate check into the model.

E.g.

public interface IClass{

    bool ShouldValidate();
}

Then, in each class:

public class Class200
{
  public bool ShouldValidate() => false; // because whatever
}

Then in your validate:

public void Validate(IClass class)
{
    if(class.ShouldValidate())
    {
        // do whatever
    }
}

This way the logic belongs to the IClass instances, and anyone willing to extend this knows exactly how to implement the exception.

Also, for classes 200-300, you can inherit them from a common base class that always returns false to have a DRY pattern.

Update Another option is putting validate inside the class directly, e.g. like so:

public interface IClass{

    void Validate();
}

Then just leaving the method empty in classes 200-300, e.g.

public class Class200
{
  public bool Validate()
  {
  }
}

and implement where needed

public class Class1
{
  public bool Validate()
  {
   // do awesome things here
  }
}
zaitsman
  • 8,984
  • 6
  • 47
  • 79
  • Got your point. But can we come up with a methodology where if condition is not used in Validate method. ? – Venkatesan Nov 26 '17 at 23:15
  • @Venkatesan That depends on what else you do inside your `Validate`. – zaitsman Nov 26 '17 at 23:31
  • @Venkatesan check my update, not sure if that is what you mean. – zaitsman Nov 26 '17 at 23:53
  • Having the class do its own validation seems like the best option to me. – Chris Nov 27 '17 at 00:05
  • @Chris that depends on how intense that other logic is, whether the class is used as a DTO/Model that is serializable, and how many dependencies that validation may have. Within the context of OPs question - sure. I would never put validation methods in my api models, though - only attributes. – zaitsman Nov 27 '17 at 00:12