Question

I have 2 classes (managed beans) in my business that of type X, the 2 classes merely have the same attributes except for 3 attributes, can i make a DTO contains all the attributes in the 2 beans and let them extends this DTO or i have to group the attributes in the DTO and associate it with the 2 beans so that each bean could set and get its attributes, i want to know the appropriate solution from the point of design, another question is it a correct design for the managed bean and the DTO to have a relation directly.

Was it helpful?

Solution

You could do that but it'd be error-prone, violating the MVC paradigm and simply a bad practice as far as I'm concerned.

Consider and compare two simple cases. First case is a bean extending a DTO and the second case is a bean containing a DTO.

Managed bean that extends a DTO

public class ContactDto {
    private String name;
}

public class ContactBean extends ContactDto {
    //has name inherited
    private boolean renderedAdminPanel;
    public void action {   }
}

In this case who will be producing managed beans? When will they be instantiated and how? Will your DAO be tightly coupled with ContacyBean? What if you decide to give up using DTOs and use detached entities instead?

All of it increases discrepancies in your architecture and makes it at the very least less manageable.

Now let's consider the alternative approach.

Managed bean that contains a DTO

public class ContactBean {
    private ContactDto contactDto;//all fields contained inside
    @PostConstruct
    public void init() {
         //get data from your service based on injected parameter's value and assign it to your DTO
    }
    private boolean renderedAdminPanel;
    public void action {   }
}

In this case all logics is crystal clear. Also, you don't need to write 'extras', because all of your properties will be available in EL context with an additional accessor. Your object's lifecycle is predictable and well-formed.


Ultimately, a DTO is a DTO and you wouldn't like to spice it up with additional and possibly secure information, like injected current user, contexts, session variables, etc. to pass that information around. Keep it simple and in its own place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top