[フレーム]
Last Updated: February 25, 2016
·
2.43K
· tellez12

C# Functional Validations

When we are validating our model, we tend to write validations like this:

public bool IsValid(Product product){

if(string.IsNullOrEmpty(product.Name))
 return false;
if(product.Price<=0)
 return false;
if(product.Category==null)
 return false; 
}

This might look OK at first but if we have a complex model, and we need to add a lot of rules, this might get messy.

A better approach is the use of delegates and lambda expressions, to create a set of rules, and then see if our product can comply them all, lets see how can we do that.

public bool IsValid (Product product){
 Func<Product,bool> rules = {
 p => string.IsNullOrEmpty(p.Name),
 p => p.Price <= 0,
 p => p.Category == null
 } 
 return rules.All( rule => !rule(product) ); 
}

In this case we have defined the same 3 rules, and are only returning true if none of the rules are true.

With this approach you can do complex validations and have a cleaner code while you are at it.

AltStyle によって変換されたページ (->オリジナル) /