(CodeCode.com) (Why Decouple) : From Validation to Immutability Protection Mechanisms

Invalid state is one of the main causes of bugs in applications. Especially in a dynamic language like PHP, applications are particularly prone to objects with invalid states.

For example, we have created an EmailService class that can send mail EmailService:: Send () :

Class EmailService {public function send(string $email) {Copy the code

The code above has a big catch. It doesn’t handle invalid $email: $email may be null, empty, or an invalid mailbox format.


A common solution to this problem is to use validation. We create an EmailValidator class:

Class EmailValidator {public function isValid(string $email) {// Validate logic}}Copy the code

Between uses of $email, we validate it. For example, in EmailService, we validate $email first and send mail only if it is valid:

class EmailService { public function send(string $email) { if (! $this->emailValidator->isValid($email)){ return; } // Send mail logic}}Copy the code

There is still a catch: at the code level, there is no guarantee that other co-developers will use EmailValidator to validate $email. Not to mention other developers, perhaps the author himself may have slipped up after a while.

Immutability protection mechanism

Instead of validating variables at run time, why not ensure that their state is valid when they are created? This pattern is the immutability protection mechanism.

Validation is a third-party activity, while protecting immutability is the variable’s own mechanism.

Refactor the above code using immutability protection:

class Email { private string $stringVal; public function __construct(string $stringVal) { if (! $this->isValid($stringVal)) { throw new \DomainException('Invalid email address'); } $this->stringVal = $stringVal; } public function toString() { return $this->stringVal; }} Class EmailService {public function send(Email $Email) {Copy the code

Using immutability protection not only solves the problems mentioned above, but also improves overall code reusability, while the Email class also provides a unified place to manage Email addresses, not to mention how this pattern improves the quality of unit tests.

(CodeCode.com) If you are also interested in TDD, DDD, and clean code, visit Our website (” Why Decouple “) to explore software development.