The Domain Model: Entity Consistency

Updated on @September 18, 2023

As we do object-oriented programming, when we create an Entity, it can accept data as constructor arguments, analyze that data, and throw exceptions when any part of it doesn't look right or leads to the entity ending up in an inconsistent or incomplete state. We can use the library beberlei/assert to do the assertions. These assertions will prevent an entity object from being instantiated with invalid data.

use Assert\Assertion; 
 
final class Order 
{
    // ...

    public function __construct( 
        int $ebookId, 
        string $emailAddress, 
        int $quantityOrdered, 
        int $pricePerUnitInCents, 
        int $orderAmountInCents 
    ) { 
        Assertion::greaterThan($ebookId, 0); 
        Assertion::email($emailAddress); 
        Assertion::greaterThan($quantityOrdered, 0); 
        Assertion::greaterThan($pricePerUnitInCents, 0); 
        Assertion::greaterThan($orderAmountInCents, 0); 
 
        $this−>ebookId = $ebookId; 
        $this−>emailAddress = $emailAddress; 
        $this−>quantityOrdered = $quantityOrdered; 
        $this−>pricePerUnitInCents = $pricePerUnitInCents; 
        $this−>orderAmountInCents = $orderAmountInCents; 
    } 
}
An Order entity that validates its constructor arguments using assertions.
🗣
Can we use these assertion functions for validating user input?” TL;DR - No. If the user fills in an invalid email address, we'd want to show a nice and friendly error message next to the email form field where the user provided it. We can't do that with the exception thrown by our entity calling Assertion::email(). If we don't catch the exception somewhere, it will just show the application's default error response. So, assertions won't be very useful when validating user input. Instead, they should be used by objects as a way to protect themselves against incomplete, inconsistent, or meaningless data. We should look for alternatives when talking back to users and informing them about their mistakes.
Bibliography