Architecture – Should DTO have validators

Architecturedtoprogramming practices

I believe that DTO should be as dummy and easy as possible. However, after hint made by my friend, opportunity to validate data that is set in DTO sounds tempting.

Let's have following example:

//this class only holds bunch of objects from the future

class FooFuture{

    /** @var ArrayObject */
    $collection;

    (other fields ommited for readability)

    /**
     * @param ArrayObject $collection
     */
    public function __construct(ArrayObject $collection = null){

         if(null === $collection){
             $this->collection = new ArrayObject();
         } else {
             $this->collection = $collection;
         } 
    }

    /**
     * @param ArrayObject $col
     */
    public function setCollection(ArrayObject $col){

        $now = new DateTime();        

        foreach($col as $element){
            if($element->getDateTime() < $now){
                throw new InvalidArgumentException('Collection should only contain objects from the future');
            }
        }
    }

    /** 
     * @return ArrayObject
     */
    public function getCollection(){
         return $this->collection;
    }

}

What do you think?

Best Answer

While i agree that it can be usefull to have validation for dto-s i think that dto-s should be as simple as possible.

You can achive boths if you are using a programming language that supports Interfaces like java or c# and put the validation logic into a seperate class that consumes interfaces.

Example

public interface IOrder { ... }

public class OrderDTO implements IOrder { ... }

public class OrderBuisinessObject implements IOrder { ... }

public class OrderValidator {
   void validate(IOrder anOrder) { ... }
}

To answer your question: yes to have validation but not in dto

Related Topic