Placing exceptions in code or in the data

Tag: algorithm Author: YUXIANGDINGXIANG Date: 2009-08-11

Most code (and most bugs) are caused by exception handling, such as: if a is checked then input fields 1, 5, 8, and 9 are required else if b is entered then input fields 3, 4, 8 are required else if a is checked and b is checked then fields 1, 3 and 8 are required

(the above is an example of buggy code since the code with the last condition is never executed since the first if a is checked will get executed and then bypass the third condition..just an example of potential bugs)

Is it better to have if/switch statements like the above in code OR to create an exception table where you would pass the conditions (select * where a is checked) and the return values indicate which fields are required (this is a simple example)...

Pros: easier to modify logic in production (update the database), simplification of code Cons: tables and assoc. logic to return the rules could become confusing, performance hit for going to the database for rule processing...

thoughts? anyone have prior experience with the database approach?

You may want to take a long hard look at existing validation frameworks: google.com/search?q=validation+framework before you go an reinvent the wheel :-)

Other Answer1

Externalising rules to some specialised "engine" may be a reasonable approach for reasons of ease of maintenance. There's quite a market for powerful rules engines.

This reflects what I see as a common outcome. You start with a few simple rules that can be easily captured in some simple data structure, but the real world is gnarly. You find that special cases abound and end up needing as much, or more, complexity as you had in your code.

That's not to say it's a bad thing to externalise, but a hope that in doing so we reduce complexity may be over optimistic - if the business is complex then so will be the rules no mater how you capture them.

That leads to anothe point, how will you manage the life-cycle of the rules. They're in production. The business wants to change them. What level of testing will you require before they go live? The very malleabiity of the rules can make us less cautious. I reckon that externalised logic is in some sense still code and needs just as much QA.