if(section1()){
if(section2()){
if(section3()){
.
.
.
// Upto 10 methods
if(section10(){
return true;
}
}
}
}
I am writing validations for 170+ controls, divided into 10 sections. As per business logic, if first section method returns true, then execute second method, else return false and show message like for ex. "Title is missing". If second method is true then execute third method and so on..
Is there an alternative to the above code? I need alternative for nested if conditions. Thanks a lot.
2
Answers
It sounds like what you really want to do is loop through and invoke these methods and for each iteration, do something with the result and decide whether or not to move on to the next step.
It’s hard to give specifics here because we don’t know what these functions do, but we know they all return a boolean value. So if any of them returns false, you probably want to break the loop and return early.
Here are a few examples/gists of C# classes you can use to implement that.
Try to nest the
ValidationSummary
andValidator
instances to simulate the nestedif()
s you had.In each validator instance, you have to set the dynamic function (stored here in
Process
) to invoke during the validation for each section.It’s a more flexible and scalable solution I think.