views:

44

answers:

2

Hi what would be the best design pattern to use for a data validation scenario where lots of values get passed to a function and all must be checked to be in the correct format and length etc. At the moment im using multiple if statements but it seems very messy.

A: 

Have a look at the specification pattern. It fits in with Domain Driven Design and has a fairly simple concept behind it.

I hope this helps.

Brendan

Burt
+1  A: 

Well, it depends what the current state of your code is right now.

I'd try to follow that:

1) try to extract similar validating code and maybe package it as seperate functions/utility modules etc., just call the function to validate, don't put validating code in the validator

2) with that, you may be able to build a master validator as a composite of validators, package sub-steps of validation in action classes, and build a big validator that will launch all of these small steps, and fail if one of the sub-tasks fail (but assess first if that is not an overkill in your case, it might be faster just to end the refactoring here, if your validation is not that complex)

3) then with that pattern in place if your validation logic changes frequently, you could try to put the configuration of the composite outside of the code. IF you have access to inversion-of-control toolkit like Spring Framework, you can potentially construct your composite from the XML configuration, and not from the code. This has an advantage, as your validation requirement change, you don't have to rebuild your project to make ammendments, and it seperated business logic from the code.

tdobek