Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Domain Driven Design - Entity and Value Object

Introduction to Domain Driven Design - Entity and Value Object

Slides from my talk at the Domain Driven Design Paris User Group in February 2013 hosted by Xebia
http://www.meetup.com/DDD-Paris/events/103367252/

Jérémie Grodziski

February 26, 2013
Tweet

More Decks by Jérémie Grodziski

Other Decks in Programming

Transcript

  1. DDD  User  Group  Paris  
    «  Introduc+on  to  Domain  Driven  Design  »  
    «  En3ty  and  Value  Object  »  
    Février  2013  

    View Slide

  2. #whoami  
    Jérémie  Grodziski  
    So>ware  Designer  and  Programmer  
    @jgrodziski  
    [email protected]  
    blog.zenmodeler.com  
    www.redsen.fr/blog  
     

    View Slide

  3. DOMAIN  DRIVEN  DESIGN  -­‐  
    INTRODUCTION  

    View Slide

  4. Why  Domain  Driven  Design?  
    DDD’s  goal  is  to  create  beEer  soFware  more  
    easily  by  focusing  on  the  domain  instead  of  the  
    technology  
    A  so>ware  is  good  if  its  capacity  to  process  
    problem  related  to  the  domain  is  good  
    – When  the  domain  is  complex  the  so>ware  is  a  lot  
    more  difficult  to  build  and  maintain.  DDD  brings  
    solu+ons  to  manage  the  domain  and  so>ware  
    complexity.  

    View Slide

  5. Domain?  
    That  knowledge  have  to  be  handled  and  automated  by  
    the  so>ware  which  helps  solving  problem  related  to  the  
    domain  
    –  Examples  :  front-­‐office  finance,  tax,  e-­‐commerce,  
    accoun+ng,  so>ware  (IDE,  Modeler)  ,  electronics,  etc.  
    The  domain  represents  a  sphere  of  knowledge  

    View Slide

  6. DDD  in  a  nutshell  
    An  Approach  
    • Design  is  driven  by  
    Models  located  in  
    par+cular  Contexts.  
    Models  are  explorated  
    in  a  crea+ve  
    collabora+on  of  
    domain  and  so>ware  
    prac++oners.  
    • An  Ubiquitous  
    Language  is  used  to  
    communicate  
    between  the  technical  
    and  the  business  side  
    Building  blocks  
    • En+ty  
    • Value  Object  
    • Service  
    • Aggregate  
    • Repository  
    • Factory  
    • Domain  Event  
    • Layered  Architecture  
    Design  principles  
    • For  design  
    suppleness  :  Supple  
    design  
    • To  preserve  the  
    model’s  integrity,  
    manage  the  design  
    effort  and  the  
    priority  :  Strategic  
    design  

    View Slide

  7. AN  APPROACH  
    An  
    Approach  
    Building  
    Blocks  
    Supple  
    Design  
    Strategic  
    Design  

    View Slide

  8. Model-­‐Driven  Design?  
    There  must  be  a  straighborward  and  very  literal  way  to  
    represent  the  domain  model  in  terms  of  so>ware  
    –  The  model  should  balance  these  2  requirements:  form  
    the  ubiquitous  language  of  the  development  team  
    and  be  representable  in  code  
    Tightly  rela3ng  the  code  to  an  underlying  model  
    gives   the   code   meaning   and   makes   the   model  
    relevant  
    Changing  the  code  means  
    changing  the  model  
    Refining  the  model  requires  
    a  change  to  the  code  
     

    View Slide

  9. Ubiquitous  Language?  
    A   language   structured   around   the   domain  
    model   and   used   by   all   team   members   to  
    connect   the   ac3vi3es   of   the   team   with   the  
    soFware.  

    View Slide

  10. Design?  
    Design  is  both  an  ac3vity  and  an  artefact  
    Design  ac3vity  is  made  of  every  decision  made  during  the  project  
    Business  analyst  are  designers  
    Developers  are  designers,  at  a  very  fine  grained  detail  level  
    Design  documenta3on  is  all  about  «  Why  ?  »  and  the  answers  leads  to  the  goals  and  
    constraints  stated  at  project  incep+on  
    Design  ac3vity  goals  is  to  deliver  the  best  solu3on  to  the  users  given  the  project  
    constraints  :  scope,  resources,  +me  and  the  most  important  one,  quality.  
    «  by  «  design  »  we  mean  a  way  of  organizing  the  domain  concepts,  which  in  turn  leads  
    to  the  way  in  which  we  organize  their  representa+on  in  code  »  Eric  Evans  
    (noun)  a  specifica+on  of  an  object,  manifested  by  an  agent,  intended  to  
    accomplish  goals,  in  a  par+cular  environment,  using  a  set  of  primi+ve  
    components,  sa+sfying  a  set  of  requirements,  subject  to  constraints  
    (verb,  transi5ve)  to  create  a  design,  in  an  environment  (where  the  designer  
    operates  

    View Slide

  11. Model?  
    «  All  models  are  wrong,  some  are  useful  »  G.  Box,  sta5s5cian  
    A  system  of  abstrac3ons  that  describes  selected  
    aspects  of  a  domain  
    A  model  describes  a  material  or  immaterial  reality  with  a  par3cular  filter  by  
    using  some  concepts  that  allows  classifying  the  observed  reality  :  these  
    filtering  concepts  goes  into  a  paradigm  and  are  formalized  through  a  
    metamodel  
    A  model  is  a  limited  and  oriented  descrip+on  of  reality  
    A  model  forms  the  basis  of  a  language  

    View Slide

  12. Good  or  Bad  Model?  
    Hence  Behavior-­‐Driven  Development  (BDD)  is  the  perfect  
    complement  to  DDD  through  scenarios  that  describe  the  
    expected  usage  !  
    A  model  is  not  good  or  bad,  a  model  is  adapted  
    to  a  usage  or  not  

    View Slide

  13. Model  example  
    This  model  describes  the  outside  
    world.  What  are  its  usage  and  
    the  objec3ve  guiding  its  
    design  ?  

    View Slide

  14. Abstrac+on  Level  
    The  act  of  abstrac3on  is  to  forget  the  non  
    significant  details  and  focus  on  the  essen3als  
    Abstrac3on  is  the  act  of  isola3ng  some  objects  shared  characteris3cs  
    In  IT,  it’s  also  the  act  of  hiding  a  component  implementa3ons  details  (object,  
    system)  that  also  leads  to  the  encapsula+on  and  interface  concept.  
    Why  abstrac+on  ?  because  a  human  brain  can  only  manage  at  most  5  
    elements  at  a  3me  (3  actually  according  to  some  psychological  studies...)  
    It’s  the  modeler’s  fundamental  intellectual  tool  
    It  separates  the  responsability  on  a  ver3cal  axis  

    View Slide

  15. Abstrac+on  Level  in  real  life  
    Would  you  prefer  dealing  with  this    
    or  that  ?  
    package
    dk.tigerteam.mdsd.demo.model.internal;
    @javax.persistence.Entity
    @javax.persistence.Table(name =
    "Customer")
    public class Customer extends
    dk.tigerteam.mdsd.demo.model.AbstractEnti
    ty {
    private static final long
    serialVersionUID = 2098912667L;
    @javax.persistence.Basic
    @javax.persistence.Column(name = "name",
    nullable = false) private String name;
    @javax.persistence.OneToOne(cascade = {
    javax.persistence.CascadeType.MERGE,
    javax.persistence.CascadeType.PERSIST,
    javax.persistence.CascadeType.REFRESH}
    , fetch =
    javax.persistence.FetchType.LAZY)
    @javax.persistence.JoinColumn(name =
    "addressId")
    @org.hibernate.validator.NotNull
    private
    dk.tigerteam.mdsd.demo.model.internal.Add
    ress address;
    @javax.persistence.OneToMany(cascade = {
    javax.persistence.CascadeType.MERGE,
    javax.persistence.CascadeType.PERSIST,
    javax.persistence.CascadeType.REFRESH}
    @javax.persistence.Basic
    @javax.persistence.Column(name =
    "comment", nullable = false) private
    String comment;
    @javax.persistence.Basic
    @javax.persistence.Temporal(javax.persist
    ence.TemporalType.TIMESTAMP)
    @javax.persistence.Column(name = "time",
    nullable = false)
    private java.util.Date time;
    @javax.persistence.Basic
    @javax.persistence.Column(name =
    "timeslot", nullable = false) private int
    timeslot;
    @javax.persistence.ManyToOne(cascade = {
    javax.persistence.CascadeType.MERGE,
    javax.persistence.CascadeType.PERSIST,
    javax.persistence.CascadeType.REFRESH}
    , fetch =
    javax.persistence.FetchType.LAZY)
    @javax.persistence.JoinColumn(nullable =
    false, name = "customerId") private
    dk.tigerteam.mdsd.demo.model.internal.Cus
    tomer customer;
    public String getComment() {
    return comment;
    public void setComment(String parameter)
    {
    } this.comment = parameter; public
    java.util.Date getTime() {
    package
    dk.tigerteam.mdsd.demo.model.internal;
    @javax.persistence.Entity
    @javax.persistence.Table(name =
    "Address") public class Address extends
    dk.tigerteam.mdsd.demo.model.AbstractEnti
    ty { private static final long
    serialVersionUID = 1697028161L;
    @javax.persistence.Basic
    @javax.persistence.Column(name =
    "street", nullable = false) private
    String street; @javax.persistence.Basic
    @javax.persistence.Column(name =
    "zipCode", nullable = false) private
    String zipCode; @javax.persistence.Basic
    @javax.persistence.Column(name = "city",
    nullable = false) private String city;
    public String getStreet() { return
    street; }
    public void setStreet(String parameter)
    { this.street = parameter; } public
    String getZipCode() { return zipCode;
    public void setZipCode(String parameter)
    { this.zipCode = parameter; } public
    String getCity() { return city; } public
    void setCity(String parameter)
    { this.city = parameter; } public
    dk.tigerteam.mdsd.demo.model.internal.Add
    ress withStreet( String street)
    { setStreet(street); return
    (dk.tigerteam.mdsd.demo.model.internal.Ad
    dress) this; public
    dk.tigerteam.mdsd.demo.model.internal.Add
    ress withZipCode( String zipCode)
    { setZipCode(zipCode); return
    (dk.tigerteam.mdsd.demo.model.internal.Ad
    dress) this; public
    dk.tigerteam.mdsd.demo.model.internal.Add
    ress withCity(String city)
    { setCity(city); return
    (dk.tigerteam.mdsd.demo.model.internal.Ad
    dress) this; } public
    dk.tigerteam.foundation.bean.mdsd.runtime
    .RuntimeMetaClazz getMetaType() { return
    metaType; }
    }
    , targetEntity =
    dk.tigerteam.mdsd.demo.model.internal.Boo
    king.class, mappedBy = "customer", fetch
    = javax.persistence.FetchType.LAZY)
    private
    java.util.Setl.internal.Booking> bookingCollection =
    new
    java.util.HashSetmodel.internal.Booking>();
    public String getName() { } return name;
    public void setName(String parameter) {
    this.name = parameter; }
    public
    dk.tigerteam.mdsd.demo.model.internal.Add
    ress getAddress() { if (address
    instanceof
    org.hibernate.proxy.HibernateProxy) {
    return time;
    public void setTime(java.util.Date
    parameter) {
    this.time = parameter

    View Slide

  16. BUILDING  BLOCKS  
    An  
    Approach  
    Building  
    Blocks  
    Supple  
    Design  
    Strategic  
    Design  

    View Slide

  17. Building  blocks  
    encapsulate with
    MODEL-DRIVEN
    DESIGN
    express model with
    isolate domain with
    encapsulate with
    ENTITIES
    VALUE OBJECTS
    LAYERED
    ARCHITECTURE
    AGGREGATES
    REPOSITORIES
    act as root of
    SMART UI
    X
    FACTORIES
    encapsulate with
    express model with
    encapsulate with
    mutually exclusive
    choices
    access with
    maintain integrity with
    access with
    SERVICES
    express model with

    View Slide

  18. Domain  
    En+ty,  Value  
    Object,  
    Service,  
    Modules  
    Applica3on  
    Services  
    User  
    Interfaces  
    Tests  
    Infrastructure  
    WS  and  
    Messaging  
    Databases  
    Programma3c    
    Interfaces  
    •  An  independent  object  
    model  serves  as  the  
    founda+on  of  the  applica+on.  
    •  Interfaces  are  defined  by  
    inner  layers,  and  
    implemented  by  outer  
    layers.  
    •  All  couplings  are  directed  
    towards  the  center  of  the  
    “onion”  
    •  It  is  possible  to  compile  and  
    run  the  core  code  of  an  
    applica3on  separately  from  
    the  infrastructure.  
    •  It  uses  the  Dependency  
    Inversion  Principle    
    So>ware  Architecture  –  from  Layers  to  «  Onion  »  

    View Slide

  19. SUPPLE  DESIGN  
    An  
    Approach  
    Building  
    Blocks  
    Supple  
    Design  
    Strategic  
    Design  

    View Slide

  20. Supple  Design  Principles  
    Inten3on  
    Revealing  
    Interfaces  
    Name  classes  and  opera+ons  to  describe  their  effect  and  purpose,  
    without  reference  to  the  means  by  which  they  do  what  they  promise    
    Side-­‐Effect-­‐Free  
    func3ons  
    opera+ons  that  return  results  with  no  observable  side  effects    
    Asser3ons   State  post-­‐condi+ons  of  opera+ons  and  invariants  of  classes  and  
    aggregates  
    Standalone  
    classes  
    Self-­‐contained  class  with  no  external  dependencies  
    Closure  of  
    opera3ons    
    An  opera+on  whose  return  type  is  the  same  as  the  type  of  its  
    arguments  in  order  to  keep  away  dependencies  against  another  types  

    View Slide

  21. STRATEGIC  DESIGN  
    An  
    Approach  
    Building  
    Blocks  
    Supple  
    Design  
    Strategic  
    Design  

    View Slide

  22. Maintaining  Model  Integrity  

    View Slide

  23. Strategic  Design  Principles  
    Context     team,  users  groups,  a  par+cular  so>ware,  a  company’s  department,  
    etc.  
    Context  
    integra3on  
    Use  the  Upstream/Downstream  metaphor.  Different  «  levels  »  :  
    An+corrup+on  layer,  conformist,  shared  kernel,  Customer/Supplier  
    rela+onship,  separate  ways,  open  host  
    Design  effort  
    prioriza3on  
    Dis+lla+ons  :  core,  support  and  generic  domains  
    Large  scale  
    structure  
    Evolving  Order,  System  Metaphor,  Responsibility  Layers,  Knowledge  
    Level,  Pluggable  Component  Framework  
    Core   idea   :   each   model   and   its   concepts   are  
    located  in  a  par3cular  context    

    View Slide

  24. Context?  
    The   seang   in   which   a   word   or   statement  
    appears  that  determines  its  meaning.  
    CONTEXT  
    There  is  no  one  model  to  rule  them  all  :  every  model  is  +ed  to  a  context  

    View Slide

  25. Context  strategy  
    Separate  
    ways  
    An+Corrup+on  
    Layer  
    Conformist  
    Customer/Supplier    
    teams  
    OpenHost  
    service  
    Shared  Kernel  
    Single    
    Bounded  Context  
    Control  of  all  associated  systems  
    Communica+ons  commitment/capability  of  teams  

    View Slide

  26. DDD  DISTILLATION  
     
    Not  all  of  a  large  system  will  be    
    well  designed.  How  to  maximize  the  impact  of  
    DDD  ?  
    bit.ly/ddd-­‐distillation  

    View Slide

  27. Is  DDD  worth  it  ?  
    Does  your  project...  
    •  Deals  with  Core  Domain  ?  
    •  Or  has  intricacy  in  the  domain/
    problem  area  you  are  trying  to  
    address  ?  
    •  Or  needs  to  bring  clarity  ?  
    •  Or  has  business  exploring  ?  not  
    so>ware  exploring.  If  they  know  what  
    their  goal  is,  but  they  don't  know  quite  
    how  to  accomplish  it.  Need  so>ware  
    development  that  can  explore  with  
    them  
    Do  you  have  what  it  takes  to  
    make  it  work?  Can  you  make  it  
    work?  
    •  Clean  bounded  context  
    •  Access  to  domain  experts.  You  must  
    obtain  access  to  domain  experts,  and  
    then  establish  a  real  rela+onship,  a  
    crea+ve  collabora+on  
    •  Skilled  team  
    •  You  want  your  internal  team  focused  
    on  the  Core  Domain  because  that  is  
    where  the  most  valuable,  specialized  
    knowledge  is.  You  want  that  core  team  
    accumula+ng  knowledge  and  skills  in  
    the  core  domain.  If  you  outsource,  you  
    may  get  a  good  piece  of  so>ware  but  
    not  that  accumulated  knowledge  

    View Slide

  28. BUILDING  BLOCKS  
    Focus  on  the  En+ty  and  Value  Object  

    View Slide

  29. DDD  Building  blocks  
    encapsulate with
    MODEL-DRIVEN
    DESIGN
    express model with
    isolate domain with
    encapsulate with
    ENTITIES
    VALUE OBJECTS
    LAYERED
    ARCHITECTURE
    AGGREGATES
    REPOSITORIES
    act as root of
    SMART UI
    X
    FACTORIES
    encapsulate with
    express model with
    encapsulate with
    mutually exclusive
    choices
    access with
    maintain integrity with
    access with
    SERVICES
    express model with

    View Slide

  30. DDD  Building  blocks  
    encapsulate with
    MODEL-DRIVEN
    DESIGN
    express model with
    isolate domain with
    encapsulate with
    ENTITIES
    VALUE OBJECTS
    LAYERED
    ARCHITECTURE
    AGGREGATES
    REPOSITORIES
    act as root of
    SMART UI
    X
    FACTORIES
    encapsulate with
    express model with
    encapsulate with
    mutually exclusive
    choices
    access with
    maintain integrity with
    access with
    SERVICES
    express model with

    View Slide

  31. VALUE  OBJECTS  

    View Slide

  32. Value?  
    Examples  :    
    –  The  number  13  
    –  A  color  (Yellow)  :  determined  by  the  propor+on  of  Red  (0),  Green  (255)  and  
    Blue  (255)  
    –  A  bank  note  of  10  €.  I  can  exchange  my  10  €  bank  note  with  yours,  it  doesn’t  
    make  a  difference  to  us  about  its  usage.  
    A  value  is  something  intangible  and  immutable  
    Intangible  =  that  exists  outside  +me  and  space  
    Immutable  =  that  doesn't  change  

    View Slide

  33. Values  Characteris+cs  
    Value  types  differ  in  the  generality  and  focus  of  their  domain    
    –  Some  are  mathema+cal:  Integers,  Double  
    –  Some  are  programma+c:  strings  (but  with  no  seman+cs  at  all...)  
    –  Some  are  real  world:  ISBNs,  Money,  Dura+on,  Phone  Number,  
    etc.  
    Value  types  reflect  constraints  
    –  ISBNs  have  a  well-­‐formedness  rule  
    –  Int  (32  bits)  is  a  bounded  subset  of  integers    
    Some  value  types  have  an  intrinsic  or  natural  ordering    
    –  Ordering  may  be  based  on  magnitude,  lexicographical  or  ordinal  
    criteria  
    –  Be  careful  about  imposing  an  ordering  on  unordered  types.  
    Ordering  is  not  an  essen+al  feature  for  all  value  types    
     
     

    View Slide

  34. Opera3ons,  Rela3onships  and  
    Constraints  form  systems  of  values    
    •  Degree  
    •  Posi+on  (Long./degree  +  Lat./degree)  :    
    •  Distance  +  Dura+on  =  Speed  (10  km/h)  
    •  Speed  +  Direc+on  =  Velocity  (10  km/h  north)  
    •  Accelera+on  =  Deriva+ve  of  Velocity  or  Speed  
    with  respect  to  +me  (3  m/s2)  

    View Slide

  35. «  Time  »  System  of  Values  
    Dura+on  :  eg.  1  Hour  or  60  seconds  
    Instant  =  seconds  since  1st  january  1970  00:00  
    |Instant  2  –  Instant  1  |  =  Dura+on  
    Instant  1  +  Dura+on  =  Instant  2  
    Interval  =  start  instant  +  end  instant  
    Timezone  
    Chronology  
    An  Instant  (point  in  +me)  is  a  value,  as  is  the  difference  between  two  
    Instant,  but  Instant,  Dura5on  and  Interval  are  not  equivalent  types.  
    See  Joda  Time  Library  for  an  implementa+on.  
    Instant  2  
    Instant  1  
    Dura+on  
    Time  

    View Slide

  36. Value  Objects  example  –  tradi+onal  
    code  
    public class CustForm extends ActionForm {
    String phone;
    public String getPhone() { return phone; }
    public void setPhone(String phone) { this.phone = phone; }
    }
    public class AddCustAction extends Action {
    CustomerService custserv = null;
    @Override
    public ActionForward execute( ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest,
    HttpServletResponse httpServletResponse) {
    CustForm form = (CustForm) actionForm;
    try {
    String phone = form.getPhone();
    custserv.addCust(0, phone, "foo");
    return actionMapping.
    findForward("success"); }
    catch (ValidationException e) {
    return actionMapping. findForward("invaliddata");
    }
    } }
    public interface CustomerService {
    void addCust(int i, String phone, String s) throws ValidationException;
    }
    public class CustomerServiceImpl implements CustomerService {
    public void addCust(int i, String phone, String s) throws ValidationException {
    PreparedStatement dbstmt = “INSERT ...”;
    if (!justnumbers(phone))
    throw new ValidationException();
    try {
    dbstmt.setInt(1, i);
    dbstmt.setString(3, phone);
    dbstmt.setString(4, s);
    dbstmt.executeUpdate();
    } catch (SQLException e) {
    throw new RuntimeException();
    }
    static boolean justnumbers(String s) {
    return s.matches("[0-9]*");
    }
    }

    View Slide

  37. Value  Objects  example  –  Phone  
    numbers  as  strings  
    class CustForm extends ActionForm
    private String phone
    class AddCustAction extends Action ... ...
    execute(...)
    String phone = form.getPhone();
    custserv.addCust(..., phone, ...);
    class CustomerServiceBean ...
    void addCust(..., String phone, ...)
    throws ValidationException ...
    if (!justnumbers(phone)) ... ...
    throw new ValidationException();
    dbstmt.setString(4, phone);
    static boolean justnumbers(String s) ...
    Form  
    Controller  
    Business  Logic  
    Persistence  

    View Slide

  38. Value  Objects  example  
    public class PhoneNumber {
    private final String number;
    public PhoneNumber(String number) {
    if(!isValid(number)) throw ...
    this.number = number; }
    public String getNumber() {
    return number; }
    static public boolean isValid(String number) {
    return number.matches("[0-9]*");
    }
    public String getAreaCode() {
    String prefix = null;
    for (int i=0; i< number.length(); i++){
    String begin = number.subString(0,i);
    if(isAreaCode(begin)) {
    prefix = begin; break; }
    return prefix; }
    private boolean isAreaCode(String prefix) { ... } }
    Make  implicit  
    concepts  explicit  !    

    View Slide

  39. Service  API  Clarity  
    FROM  
    void  addCustomer(String,  String,  String,  
    int,  int,  String,  String,  boolean)    
    TO  
    void  addCustomer(Name,  PhoneNumber,  PhoneNumber,  
    CreditStatus,  
    SalesRepId,  
    Name,  PhoneNumber,  PartnerStatus)  

    View Slide

  40. Value  Objects  prac+cal  +ps  
    Construc3on  should  result  in  a  meaningful  and  well-­‐formed  object  
    –  Par+al  ini+alisa+on  is  problema+c  for  objects  —  especially  for  value  objects    
    –  Consider  the  constructor  to  be  transac3onal:  it  returns  a  correct  object  or  an  
    excep+on  
    Respect  and  enforce  state  invariant  
    Comparison…  
    –  Equality  is  a  fundamental  concept  
    –  Total  ordering  may  or  may  not  apply    
    Classifica3on  and  conversion…  
    –  Avoid  inheritance  and  favor  composi+on  
    –  May  support  conversions  (Km  -­‐>  Miles),  (Hour  -­‐>  Second)  
    Value  Object  Smells  :  
    –  Anemic  Value  Object  :  Lizle  behaviour  beyond  field  access    
    –  Role  creep  :  Too  much  responsibility  and  external  dependencies    
    –  Non-­‐meaningful  constructor  
    –  Constructor  without  useful  enforcement  or  sufficient  quality  of  failure    

    View Slide

  41. DTO  vs  VO  
    DTO  –  Data  Transfer  Object  
    –  purpose:  data  transfer  –  technical  construct  
    –  bunch  of  data  –  not  necessarily  coherent  
    –  no/lizle  behaviour    
    VO  –  Value  Object  
    –  purpose:  domain  representa+on  
    –  high-­‐coherent  data  
    –  rich  on  behaviour    
    «  Data  Transfer  Object  is  an  oxymoron.  »  Dan  North,  Qcon  
    London  2011  Conference  

    View Slide

  42. Value  Objects  
    Descrip+on  
    •  Many  objects  have  no  conceptual  iden5ty.  
    These  objects  describe  some  characteris5c  
    of  a  thing.  
    •  Tracking  the  iden+ty  of  en++es  is  
    essen+al,  but  azaching  iden+ty  to  other  
    objects  can  hurt  system  performance,  
    add  analy+cal  work,  and  muddle  the  
    model  by  making  all  objects  look  the  
    same.  
    •  So>ware  design  is  a  constant  bazle  with  
    complexity.  We  must  make  dis+nc+ons  so  
    that  special  handling  is  applied  only  
    where  necessary.  However,  if  we  think  of  
    this  category  of  object  as  just  the  absence  
    of  iden+ty,  we  haven’t  added  much  to  
    our  toolbox  or  vocabulary.  In  fact,  these  
    objects  have  characteris+cs  of  their  own,  
    and  their  own  significance  to  the  model.  
    These  are  the  objects  that  describe  things.    
    Therefore  
    •  When  you  care  only  about  the  aEributes  
    of  an  element  of  the  model,  classify  it  as  
    a  value  object.    
    •  Make  it  express  the  meaning  of  the  
    aEributes  it  conveys  and  give  it  related  
    func3onality.    
    •  Treat  the  value  object  as  immutable.    
    •  Don’t  give  it  any  iden3ty  and  avoid  the  
    design  complexi3es  necessary  to  
    maintain  en33es.  

    View Slide

  43. Value  Objects  benefits  
    Computa3on  complexity  moved  to  value  objects    
    Adding  new  terminology  to  language  
    Compound  value  objects  can  swallow  lots  of  
    computa3onal  complexity  
    Provides  advanced  language    
    En3ty  relieved  of  complexity    
    Uses  advanced  language    
    Improved  extensibility    
    Especially  clarity,  testability  and  concurrency  issues  

    View Slide

  44. ENTITIES  

    View Slide

  45. En+ty?  
    Some  objects  have  a  con3nuity  and  a  fixed  iden3ty  whatever  
    values  their  states  or  azributes  are  
    Iden33es  are  mental  tools  we  use  to  superimpose  con3nuity  
    on  a  world  which  is  constantly,  func3onally,  crea3ng  new  
    values  of  itself  
    By  iden+ty  we  mean  a  stable  logical  en+ty  associated  with  a  series  
    of  different  values  over  +me  
    An  En5ty  is  an  object  that  is  not  defined  by  its  
    azributes  but  rather  by  a  thread  of  con+nuity  
    and  its  iden+ty  

    View Slide

  46. En+ty  
    An  en3ty  is  an  object  that  has  an  iden3ty  and  a  
    state,  so:  
    What  does  it  means  to  be  the  same  thing  ?  
    How  dis+nguish  between  two  different  objects  ?  
    Its  naming  uses  a  nominal  group  that  refers  to  
    something  or  a  role  
    Examples  :  
    A  credit  card  :  has  an  iden+ty  (number)  and  a  state,  that’s  why  
    there  is  a  chip  in  it  in  Europe  
    A  person  in  a  plane  is  an  En5ty  because  a  seat  is  associated  with  
    her.  A  person  in  a  bus  is  a  Value  Object  because  her  iden+ty  
    doesn’t  mazers  (or  with  low-­‐cost  air  carrier).  It  depends  of  the  
    context…  
     

    View Slide

  47. En++es  
    Descrip+on  
    •  Many  objects  are  not  fundamentally  defined  
    by  their  aOributes,  but  rather  by  a  thread  of  
    con5nuity  and  iden5ty.  
    •  Some  objects  are  not  defined  primarily  by  
    their  azributes.  They  represent  a  thread  of  
    iden+ty  that  runs  through  +me  and  o>en  
    across  dis+nct  representa+ons.  Some+mes  
    such  an  object  must  be  matched  with  
    another  object  even  though  azributes  differ.  
    An  object  must  be  dis+nguished  from  other  
    objects  even  though  they  might  have  the  
    same  azributes.  Mistaken  iden+ty  can  lead  
    to  data  corrup+on.  
    Therefore  
    •  When  an  object  is  dis3nguished  by  its  
    iden3ty,  rather  than  its  aEributes,  make  
    this  primary  to  its  defini3on  in  the  model.    
    •  Keep  the  class  defini3on  simple  and  
    focused  on  life  cycle  con3nuity  and  
    iden3ty.    
    •  Define  a  means  of  dis3nguishing  each  
    object  regardless  of  its  form  or  history.    
    •  Be  alert  to  requirements  that  call  for  
    matching  objects  by  aEributes.    
    •  Define  an  opera3on  that  is  guaranteed  to  
    produce  a  unique  result  for  each  object,  
    possibly  by  aEaching  a  symbol  that  is  
    guaranteed  unique.  This  means  of  
    iden3fica3on  may  come  from  the  outside,  
    or  it  may  be  an  arbitrary  iden3fier  created  
    by  and  for  the  system,  but  it  must  
    correspond  to  the  iden3ty  dis3nc3ons  in  
    the  model.    
    •  The  model  must  define  what  it  means  to  be  
    the  same  thing.  

    View Slide

  48. The  Iden+ty  Opera+on  
    Each  ENTITY  must  have  an  opera+onal  way  of  establishing  its  
    iden+ty  with  another  object—dis+nguishable  even  from  
    another  object  with  the  same  descrip+ve  azributes  
    An  iden+fying  azribute  must  be  guaranteed  to  be  unique  
    within  the  system  however  that  system  is  defined—even  if  
    distributed,  even  when  objects  are  archived  
    See  UUID,  Master  Data  Management  Mechanisms,  etc.  

    View Slide

  49. Is  it  an  En+ty  or  a  Value  Object?  
    It  depends...  
    If  the  object  has  a  lifecycle  then  are  you  interested  
    in  it?  

    View Slide

  50. Value  Objects  rela+on  with  En5ty  
    Value  objects  capture  the  state  of  other  (en3ty)  objects.  
    What  is  interes+ng  about  them  is  not  their  iden+ty  but  
    the  value  that  they  represent  
    From  a  programming  perspec+ve,  we  can  model  values  
    as  objects    
    –  Hence  value  objects  and  value  types  
    –  Value  objects  have  significant  state  but  insignificant  
    iden+ty  
    –  A  value  object  is  a  kind  or  style  of  object  that  realises  a  
    value    
     

    View Slide

  51. En+ty  vs  Value  Object  
    Characteris3c     Value  Object   En3ty  
    Mutability   Should  be  immutable   Usually  mutable    
    Equality     Compare  by  value,  as  in  a.equals(b)   Compare  by  iden+ty,  as  in  
    a==b  
    Scale   Typically  small  in  scale     Of  any  size  
    Serializability     Should  be  serializable;  may  be  
    parseable  
    Need  not  be  serializable    
    Defaults     O>en  have  a  natural  default:  the  
    number  0,  or  “today  »  
    No  natural  default  
    Comparability   O>en  have  a  natural  order:  1,  2,  
    3.  .  .  
    Typically  no  natural  sort  
    order  
    Closure  (or  Algebra)   O>en  have  a  closed  set  of  
    opera+ons:  2  +  2  =  4  
    Unlikely  to  have  any  closed  
    set  of  opera+ons    
    Iden3ty     May  represent  an  iden+fier,  such  as  
    an  SSN  
    Something  that  is  iden+-­‐  
    fied,  such  as  a  Person    
    User  Interface     Have  dedicated  widgets:  checkbox,  
    calendar.  .  .    
    Coded  by  hand  

    View Slide

  52. OBJECT-­‐ORIENTED  PARADIGM  
    Let’s  get  back  to  the  roots  

    View Slide

  53. Object  paradigm  -­‐  roots  
    Alan  Cur3s  Kay  (born  May  17,  1940)  is  
    an  American  computer  scien+st,  known  for  his  early  
    pioneering  work  on  object-­‐oriented  programming  (with  
    Smalltalk)  and  windowing  graphical  user  interface  design,  
    and  for  coining  the  phrase,  "The  best  way  to  predict  the  
    future  is  to  invent  it.”  
    "OOP  to  me  means  only  messaging,  local  reten6on  and  
    protec6on  and  hiding  of  state-­‐process,  and  extreme  late-­‐
    binding  of  all  things.”  Alan  Kay  
    http://www.purl.org/stefan_ram/pub/doc_kay_oop_en  

    View Slide

  54. Is  state  bad  ?  
    Stateful  
    Stateless  

    View Slide

  55. State?  
    State  is  o>en  «  summarized  »  with  a  past  par3ciple  that  have  
    a  sta3c  and  stable  meaning  (paid  order,  loggued  user,  etc.)  
    State  influences  the  object’s  behavior  
    State,  in  its  defini+on,  imply  that  between  several  different  
    stable  states,  there  are  en+ty’s  transforma3ons  occuring  
    during  a  state  transi6on  triggered  by  an  event  
    A  state  is  associated  with  an  iden6ty  in  order  to  track  the  
    different  state  transi5ons  
    A  state  is  a  rela+on  among  individual  en++es  and  
    values  at  a  par+cular  instant;  it  can  change  over  
    +me  

    View Slide

  56. State  –  example  
    High  visibility  and  low  mutability  
    data  in  the  Informa+on  System  
    Immutable,  con+nuous  
    Immutable,  con+nuous  
    Mutable,  con+nuous  
    Mutable,  discrete  
    Immutable,  con+nuous  
    Immutable,  discrete  
    Events  that  triggers  state  transi+on  

    View Slide

  57. State  Transi+ons  -­‐  example  
    State-­‐transi+on  Diagram  example  for  a  Person  
    object  

    View Slide

  58. Temporal  aspect  of  State  management  
    and  Iden5ty  
    Iden3ty  
    Single   Married  
    Adult  
    Minor  
    Time  
    Adult  state  
    Marital  state   Divorced  
    •  Business  Id  :  12345678  
    •  John  
    •  Doe  
    •  5  November  1976  in  Paris  
    •  …  
    En3ty  
    State  
    En5ty  Object  at  a  given  
    moment  in  +me  
    Iden3ty   State  

    View Slide

  59. State,  Iden+ty  and  Func+on  or  the  
    Saint-­‐Graal  of  mixing  OO  and  FP  
    State  
    Iden3ty  
    State  1   State  2   State  3  
    Func+on   Func+on  
    Event  triggers   Event  triggers  
    •  value  1a  
    •  value  1b  
    •  value  1c  
    •  value  1a  
    •  value  1b  
    •  value  1c  
    •  value  2a  
    •  value  2b  
    •  value  1a  
    •  value  1b  
    •  value  1c  
    •  value  2a  
    •  value  2b  
    •  value  3a  
    Publish  Internal  
    Event  
    Publish  Internal  
    Event  
    ...  
    Time  

    View Slide

  60. Example  with  Order  en+ty  
    Iden3ty  :  Order  N°  123456  
    Submized   Paid   Shipped  
    pay   ship  
    Payment  details  
    from  Payment  
    Gateway  received  
    Carrier  data  
    q  Customer  Data  
    q  Product  Lines  
    (product  +  qty)  
    q  Shipping  Data  
    States  
    submit  
    q  Customer  Data  
    q  Product  Lines  
    (product  +  qty)  
    q  Shipping  Data  
    q  Payment  Data  
    q  Customer  Data  
    q  Product  Lines  
    (product  +  qty)  
    q  Shipping  Data  
    q  Payment  Data  
    q  Carrier  Data  
    Front  website  form  
    submized  
    Order  submized  
    event   Order  paid  event   Order  shipped  
    event  
    Time  

    View Slide

  61. Essen+al  OO  concepts
       
    Objects  have  a  state,  a  behavior  and  an  iden3ty.  
    Encapsula3on  allows  to  focus  on  the  external  
    proper3es,  the  object  interface,  while  hiding  
    internal  mechanisms.    
    Objects  communicates  by  messages  through  
    rela3onships.    
    Class  defines  objects  set  that  share  the  same  
    proper+es.  Class  are  object  factory.    
    Generaliza3on  rela+onship  allows  to  factorize  
    common  proper+es  and  permits  polymorphism.    
    Object  lifecycle  is  described  by  a  finite  state  machine  
    that  react  to  events.  

    View Slide

  62. Essen+al  FP  concepts    
    Nested,  first-­‐class  func3ons  
    Means  of  composing  func3ons  with  
    other  func+ons  to  solve  problems  
    Immutability  [and  no  side-­‐effects  but  to  
    a  certain  degree  according  to  the  
    interlocutor’s  religion,  Haskell  or  Lisp]  
    Few  Data  Structures,  Lot  of  Opera3ons  
    Recursion  
    Lazyness  
     
    First-­‐Class  Func3on  
    Immutability  
    Recursion/Lazyness  

    View Slide

  63. DDD’s  Essen+als  
    Crea3ve  collabora3on  of  domain  experts  and  soFware  
    experts  :  what  is  the  value  the  domain  expert  acquired  during  
    the  modeling  process?  it  must  be  a  crea+ve  process  
    Explora3on  and  experimenta3on  :  exploring  model  is  really  
    cheap  (on  the  black  board),  we  do  not  finish  un+l  we  produce  3  
    bad  models,  if  you  only  produce  good  things  you  are  not  
    crea+ve.  We  need  to  discuss,  let's  celebrate  the  bad  ideas  !    
    Emerging  models  shaping  and  reshaping  the  ubiquitous  
    language  
    Explicit  context  boundaries  
    Focus  on  the  core  domain  

    View Slide

  64. Designer’s  key  sentences  
    It’s  all  about  the  language  
    Make  the  implicit  explicit  
    Get  real  and  concrete  usage  through  scenarios  
    There  is  no  one  model  to  rule  them  all:  every  model  is  +ed  to  a  
    context  
    Not  all  domains  are  equivalent,  some  are  more  important  than  
    other  :  the  core  domain  
    Collabora5on  between  domain  expert  and  so>ware  expert  is  the  
    key  :  if  you  want  to  go  fast,  go  alone,  if  you  want  to  go  far,  go  
    together...  

    View Slide

  65. Content’s  azribu+on  
    Some  of  this  presenta+on’s  content  comes  
    from  :  
    Domain  Driven  Design  –  PaEern  Summaries  
    Distributed  under  the  Crea+ve  Commons  Deed:  
    Azribu+on  2.0.  You  are  free:    
    •  to  copy,  distribute,  display,  and  perform  the  work    
    •  to  make  deriva+ve  works    
    •  to  make  commercial  use  of  the  work  
    AEribu3on  :  Eric  Evans,  DOMAIN-­‐DRIVEN  
    DESIGN,  Tackling  complexity  in  the  Hearth  of  
    So>ware  Addison-­‐Wesley,  ©  Eric  Evans,  2004.  
    Eric  Evans,  
    Domain  Driven  
    Design’s  author  
     

    View Slide