Sunday, December 11, 2011

jDTO Binder - Immutable DTOs

jDTO Binder 0.6 is out and with one new great feature. A really good practice in java is to minimize mutability of objects and with this you gain thread safety and also you can optimize memory by creating an instance pool; jDTO Binder can now instantiate objects by using a constructor other than the default and therefore making possible immutable DTO's

In order to take advantage of this feature, your DTO class should have one or more constructors with arguments and none default constructor. Also since some limitations of the Java Reflection API you need to configure each constructor argument to specify which will be the source value.

The following is an example of an immutable DTO:
public final class SimpleImmutableDTO {
    private final String firstString;
    private final String secondString;
    
    //make this the DTO constructor.
    @DTOConstructor
    public SimpleImmutableDTO(@Source("myString") String firstString, @Source("related.aString") String secondString) {
        this.firstString = firstString;
        this.secondString = secondString;
    }
    
    public SimpleImmutableDTO(String firstString, String secondString, String thirdString) {
        this.firstString = firstString;
        this.secondString = secondString;
    }
    
    public String getFirstString() {
        return firstString;
    }

    public String getSecondString() {
        return secondString;
    }
    
}

Immutable DTOs can take advantage of all of the features regular DTOs can except for "transient" constructor arguments which at the time doesn't make sense to me.

Also this feature is enabled for XML configuration:
<dto type="com.juancavallotti.jdto.dtos.SimpleImmutableDTO">
    <immutableConstructor>
        <arg type="java.lang.String">
            <source name="myString" />
        </arg>
        <arg type="java.lang.String">
            <source name="related.aString" />
        </arg>
    </immutableConstructor>
</dto>

No comments:

Post a Comment