Rules like ‘A parent object will have up to 2 children’ could be enforced in database using triggers. But would it be a good idea to duplicate the rule if this rule is already enforced in the domain layer.
In which cases duplication of such rules are justified? Are there any alternative to avoid such duplication? Is it not a data integrity rule?
Thanks
It’s virtually impossible to do this correctly in code that’s outside the database. Any code that looks to see if 2 records already exist and if not then allows a new record to be added can be fooled by 2 threads operating simultaneously on the same parent. Unless you actually lock the database table or somehow serialize the child addition process, either of which create a real lack of scalability.
You don’t mention the RDBMS so it’s hard to give you a solution.
EDIT:
I agree with those who say that triggers are far from clean. But they are not the only way to enforce rules within a database. That is why I said without knowing your RDBMS, it would be impossible to suggest any database solution or even one that may not require a trigger.
Beside, you shouldn’t need a trigger because your middle tier never does DML, it just calls database procedures or packages which encapsulate your CRUD. RIght?!