Sujets
dto | architecture | hexagonal | mapper | assembler

Exemple DTO

Exemple de l’utilisation d’un DTO et de son convertisseur afin de protéger un domaine.

//Note: Inspiré de DDD Sample

public interface Cargo { //< Dans le DOMAINE
  TrackingId trackingId();
  void specifyNewRoute(RouteSpecification route);
  void dockAt(UnLocode unLocode);
  void load();
  void unload();
  void leaveDock();
  boolean isMisguided();
  boolean isDelivered();
  HandlingHistory handlingHistory();
}
public class CargoMapper {

  public CargoDto toDto(Cargo cargo) {
    String trackingId = cargo.trackingId().toString();
    HandlingEvent lastHandlingEvent = cargo.handlingHistory().lastEvent();
    CargoActivityDto lastActivity = CargoActivityMapper.mapDto(lastHandlingEvent);
    boolean misguided = cargo.isMisguided();
    boolean delivered = cargo.isDelivered();

    return new CargoDto(trackingId, lastActivity, misguided, delivered);
  }

}

public class CargoActivityMapper {

  public CargoActivityDto toDto(HandlingEvent handlingEvent) {
    return new CargoActivityDto(handlingEvent.unLocode(), handlingEvent.action(), handlingEvent.date());
  }

}
public class CargoDto { //< Couplé avec le UI (API)

  public final String trackingId;
  public final CargoActivityDto lastActivity;
  public final boolean misguided;
  public final boolean delivered;

  public CargoDto(String trackingId, CargoActivityDto lastActivity, boolean misguided, boolean delivered) {
    this.trackingId = trackingId;
    this.lastActivity = lastActivity;
    this.misguided = misguided;
    this.delivered = delivered;
  }

}

public class CargoActivityDto {

  public final String location;
  public final String action;
  public final Instant date;

  public CargoActivityDto(String location, String action, Instant date) {
    this.location = location;
    this.action = action;
    this.date = date;
  }

}