DEV Community

Cover image for Code Smell 121 - String Validations
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 121 - String Validations

You need to validate strings. So you don't need strings at all

TL;DR: Search for missing domain objects when validating strings.

Problems

  • Primitive obsession.

  • Bijection Fault

  • Validated strings are a subset of all possible strings.

  • Fail Fast principle violation.

  • Single Responsibility Principle violation.

  • DRY Principle Violation.

Solutions

  1. Create a first-class object representing the concept under the MAPPER

Context

Serious software has lots of string validations.

Often, They are not in the correct places.

This leads to non-robust and corrupt software.

The simple solution is to build only real-world and valid abstractions.

Sample Code

Wrong

<?

//First Example: Address Validation
class Address { 
  function __construct(string $emailAddress) {
     //String validation on Address class violates SRP
     $this->validateEmail($emailAdress);
     //...
   }

  private function validateEmail(string $emailAddress) {
    $regex = "/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/";
    //Regex is a sample / It might be wrong
    //Emails and Urls should be first class objects

    if (