Reputation: 3870
I have a problem where I'm submitting a form and prior to submitting the form I have to define certain criteria for that form which means when the form is submitted it goes through the criteria and if the criteria is met it performs an action.
Now it leads me to a lot of if/else conditions and I'm wondering how can I avoid this. I'm also concerned about performance issues as well. Is there any design pattern suitable for this? How should I store the data? What data structure might be useful in this case?
Upvotes: 2
Views: 37
Reputation: 32946
Based on your description you could have either a collection of validators or a chain of responsibility for validation.
In either case each validator class has the responsibility for doing one small part of the validation and only if all validation succeeds do you perform the final action.
if your validations are of the form
if (someFlag)
{
if (form.SomeProperty!= validValue) return false
}
else
{
if (form.SomeOtherProperty!= validValue) return false
}
if (someOtherFlag)
{
if (form.SomeThirdProperty!= validValue) return false
}
else
{
if (form.SomeForthProperty!= validValue) return false
}
all repeated one after the other then I would favour a simple collection of validators and just loop round them all checking each one and return false as soon as one fails and do the action if the all succeed.
if they are more deeply nested with certain checks only being done in certain situations, a bit like this:
if (someFlag)
{
if (form.SomeProperty!= validValue)
{
return false
}
if (someDependentFlag)
{
if (form.SomeThirdProperty!= validValue)
{
return false
}
if (someOtherDependentFlag)
{
if (form.YetAnotherField != changedValue) return false
}
}
}
else
{
if (form.SomeProperty2!= validValue)
{
return false
}
if (someOtherDependentFlag)
{
if (form.SomeThirdProperty!= validValue)
{
return false
}
if (someOtherDependentFlag2)
{
if (form.YetAnotherField2 != changedValue) return false
}
}
}
Then I would favor the chaining approach, as you can encapsulate each check as an individual class and chain then together as necessary and as deeply nested as you like.
You could have a combination approach if most checks are simple but a couple have some nesting, as long as your validators all implement the same interface.
Start with the simplest thing you can, and evolve to more complexity if you need it.
Upvotes: 1