Tuesday 23 June 2020

Using a DDD Approach for Validating Business Rules

When you think about business rules, especially if you are a technical person, you probably imagine lines of code or a business rules engine (if you use one). However, rules are more related to knowledge management than coding. For instance, a person working in the construction sector knows there are many rules about the minimum size of a bedroom or what are required characteristics for a space to be considered a bedroom instead of a den. Knowing the rules and how to apply them make this person an expert in this domain. Our goal is to create software applications that emulate the behavior of domain experts.
For the rest of the article, I’m going to use a system for reserving shared company’s resources. The goal of this system will be to help employees make a reservation of things like notebooks, projectors, table tennis tables, etc.
Just by reading this first sentence, you probably can generate a quick list of questions like, what is a resource? What does it mean to book a resource? Does the system allow a resource to be booked more than once? Questions like these should be answered by the domain expert and will be the business rules that control the behavior of the system.
This also will guide the definition of entities, value objects, commands, and other elements of the system. How to define each element is beyond the scope of this article.
This article will cover only the part of how to structure business rules that:

  1. Are consistent. Organizing rules in a way that any developer can understand is paramount for any future change. It would be best if you considered that systems always change and that applications should be prepared for such changes.
  2. Are easy to test. Making testable rules is the only way to guarantee that changes are not going to break existing functionalities.
  3. Maintain data consistency. Keeping data consistent is one of the primary responsibilities of the business rules. In my personal experience, many data quality issues are related to poor handling of the system rules.
  4. Are easy to diagnose. We should aim to avoid any unexpected error; however, exceptions are always going to happen. Such errors are even worse when the only diagnostic information you have says object reference null.
This article uses the input-process-output model to express the system rules. In this model, an input is provided to the system; an internal processor takes the input and executes operations, which create an output. But before the processor can perform any action, it must validate that the provided information is valid. The next sections describe how to handle these validations.
https://www.infoq.com/articles/ddd-business-rules/