views:

217

answers:

2

I'm refactoring a large legacy web application that has some complicated forms.

These forms use javascript to display or hide fields on the basis of other entered fields. E.g ticking a checkbox for "second address" reveals a set of other fields to enter.

The current validation for this consists of lots of deeply nested if statements. Similar to:

if(checkboxTicked) {
  haveMandatoryAddressFieldsBeenEntered();
   if(addressHasbeenFilledIn) {
        validateAddress()
   }
}

Now imagine this example with much deeper nesting!

My question is - is there a nice pattern or best practice that I can refactor this with?

For reference I'm using Spring MVC - but I guess this would apply across multiple technologies.

+1  A: 

When using MVC, I put my validation in my model. The model and controller don't know about how the form in the view looks like.

Paco
A: 

you could use a similar idea, with a bool keepGoing.

bool keepgoing=true;
if(checkboxTicked) {
  keepgoing=haveMandatoryAddressFieldsBeenEntered();
   if(keepgoing) {
        keepgoing=validateAddress()
   }
next if//
}

THis is just a quick idea I put down, it would save your nesting, but have the same control flow, maybe making things easier to read.

CrazyJugglerDrummer