I am looking for some best practices/patterns to transform objects from one to another. I load the data from DB using DAO to create my domain objects. In my application I need to transform into a different object that acts as an input to another module.
For example, the customer is the domain object which holds a list of orders. I need to transform this into a object customerorder.
Public class Customer {
String customerid
List<Order> orders
}
Public class Order {
Integer id
Date orderDate
}
/** Transformed objects **/
public class CustomerOrder {
string customerid
Integer orderid
}
Currently I have an interface CustomerDTO which has a method to return a list of CustomerOrder objects and a concrete class implementing the interface
Public interface CustomerDTO {
List<CustomerOrder> getData(Date date)
}
Public class CustomerDTOImpl implements CustomerDTO {
Private Customer customer
Public CustomerDTOImpl(Customer customer) {
this.customer = customer
}
Public List<CustomerOrder> getData(Date date) {
..... Code to loop through orders and create and return a list with matching order dates
}
}
For simple, transformations I don’t need a DTO class but my transdormations are very complex and I would like to keep the transformation logic separate for different objects.
Initially I had a transformer class which just loops through all the objects and create transformed objects but I don’t think that was a good design and thought of this DTO. But I believe there are better ways to do it.
Also I need to be able to use the DTO pattern on several objects. In this Customer was just one such object? I have 20 like diffent objects that I need to transform into their respective transformed objects.
Any thoughts on best practices and pattern would be very useful. Also is there any generics I could use to scale them better.
Thanks
Javid
You need to have the object extend or implement another object so that you can cast them as different kinds of objects. I suggest looking into Polymorphism to do this. The name sounds scary, but it’s no big deal