State composition

From cdd
Jump to: navigation, search

CDD uses composition, also known as aggregate in DDD, when building more complex objects:

CDD-state-composition.png


This is best explained by an example. Create states for address:

package com.myproject;
 
public class AddressState {
    String streetName;
    int streetNumber;
    int zipcode;
}


...and person + generate:

package com.myproject;
 
import net.sf.laja.cdd.annotation.Key;
 
public class PersonState {
    @Key int ssn;
    String givenName;
    String surname;
    AddressState address;
}


Note that the attribute address should be named address and not addressState.


...add creators for address:

package com.myproject;
 
public class AddressCreator {
    AddressState state;
}

...and person:

package com.myproject;
 
public class PersonCreator {
    private PersonState state;
}


...regenerate and execute (make sure AddressCreator.createAddress and PersonCreator.createPerson are included):

PersonState person = createPerson()
        .ssn(112233)
        .givenName("Carl")
        .surname("Carlson")
        .address(createAddress().streetName("First street").streetNumber(123).zipcode(75432))
        .asState();
 
System.out.println(person);


output:

{ssn=112233, givenName="Carl", surname="Carlson", address={streetName="First street", streetNumber=123, zipcode=75432}}


Substates can include other substates (including itself if representing a parent/child relationship). We could for example let AddressState include ZipcodeState, but we leave that exercise to the reader! If you're curious about how to work with composition, you can go directly to the section Composition.


< Back          Next >