Rule of Law
Rule of Law is a logical predicate language and a tool that allows you to verify assumptions about data and relationships in your database that are otherwise hard to check or enforce.
Think of Rule of Law as a last line of defense, to provide a safety-net for cases that normal database constaints cannot cover.
Here's an example:
rule "All completed orders must have a completion date" forall orders o: o.status = "COMPLETE" => o.date_completed != NULL
Read the above as "for every order in the DB it should hold that if its status is COMPLETE, then it must also have a completion date". Note that this expression says nothing about non-COMPLETE orders.
One could also state the opposite: "for every order in the DB it should hold that if it has a completion date, then it must also be in COMPLETE status":
rule "All orders with a completion date must be complete" forall orders o: o.date_completed != NULL => o.status = "COMPLETE"
Since this arrow holds both ways, these two rules can be combined into a single rule with an equivalence relation:
rule "All completed orders have a completion date, and all others do not" forall orders o: o.date_completed != NULL <=> o.status = "COMPLETE"
Codifying these rules as logical statements serves multiple purposes:
- Share common system knowledge. By making the rules explicit, they become an expression of intent.
- Explicit documentation.
- One place to look. Since all rules can be stored in the same place, it's easy to find.
- Proactive monitoring. Since these rules are self-validating, we can periodically run them as checks against real production data and alert as soon as a counter example is found.
- Test cases. By running the rules as part of the CI / testing phase, you can catch broken assumptions as they happen.
- Guide code reviews. Because the rules are explicitly stored and versioned alongside code, they allow us to link to a rule when reviewing code.
- Part of the developer workflow. While working on new code, formulate a one-off rule and verify it quickly against real data.