I have some experience with Django and its MVC (MTV rather...) concept. In my previous project in django, I always tried pack a lot of functions (methods) to Model class - all which could work on single entity in Model object. I know that in Java EE world, there is much more layers than 3, so how should I do it in Spring? For instance, where should I place function which sum up few properties of entity? Anyway, do models in spring are also called "model"?
Just apply good OO practices. If some behavior can be encapsulated in the Model class, then definitely put it in the Model class. For example, a Model having a salary and a bonus properties might of course have a getTotalIncome method which returns the sum of salary and bonus.
Of course, it shouldn't cross its own boudaries. If the computation of the total income necessitates the call of a service to apply some tax based on the current month and some configuration in the database, this becomes business logic and couples your model objet with the service layer, which should not be done. So the getTotalIncome method in this case should not exist anymore.
Typically, no, you dont add many functions in the model object itself. And spring is all about good design. In other words, the model should just be a container for the information representing model elements. Everything that is done to the model should be done through things like DAO. In spring my models usually look like this:
public class Car {
private int id;
private Engine engine;
private Control steeringWheel;
...
// getters and setters
}
With a DAO like:
public interface CarDao {
public void add( Car car );
public void update( int id, Car car );
...
}
It's less about layers and more about keeping data objects simple so that you can move them around your enterprise systems in whichever way you like without surprises. There's nothing about Spring itself that really cares how many methods you put in a class, but I agree with Lucas that keeping an entity class simple is better design.
Long experience has led me back to this conclusion many times. "Busy" entity objects end up being a pain sooner or later.
Ok, I would have a model object for Player, one for Game, and maybe one for State. I would have a DAO for each and, I would have a controller, perhaps called Controller that would perform all of the operations. For example:
public class Player {
private String name;
...
}
public class State {
private Map<Player, Location> locations;
private Map<Player, Health> healths;
...
}
public class Game {
private Player player1;
private Player player2;
private State state;
...
}
With a standard CRUD like DAO (possibly with additional helper methods), and a controller that implements an interface something like this:
public interface Controller {
public void move( Player player, Location location );
...
}
Java EE has changed a lot of patterns that were common in J2EE world. Although Spring is not Java EE it was designed around the same idea - to get rid of the legacy J2EE cumbersomeness. There's a good book by Adam Bien about J2EE patterns that have become anti-patterns - "Real World Java EE Patterns.
Rethinking Best Practices"
One of it chapters "Persistent Domain Object" answers exactly your question. Model your application with real objects and don’t care about the persistence at the beginning... JPA turns out to be really flexible in mapping rich domain objects into relational tables. The more complex logic you have to realize, the easier object-oriented persistence can be maintained and developed.
Related
Where should I keep logic for derived fields (derived from attributes of the same model class) - in model layer or in service layer?
Example:
In the code below, age is derived from dateOfBirth (do not ask why you need to persist age when it can be derived from dateOfBirth in the model class - this is a hypothetical example). Where should I keep calculateAge() method - in PersonModel or PersonService?
import java.util.Date;
models/Person.java
#Entity
public class Person {
private Date dateOfBirth;
private String age;
}
service/PersonService.java
public interface PersonService {
}
Not sure what you mean by "where to keep it", but this usually depends if you want to treat your entity model as domain or persistence model. Lots of people don't need to distinguish between these two models(because the differences are minimal) and just put everything into the entity class. As soon as the domain logic becomes more important, people usually introduce some sort of domain model on top of the entity model, within which the entity state is encapsulated, and translation between the models happens in the service layer implementation.
This is an open ended question, so you won't get a definitive answer. This is just what I observed from other projects and how I understand this is usually done or supposed to be. Do what works best for you and always ask yourself if the abstraction brings value to your project before applying a design pattern like this.
Short version
Why would we ever need factories (being injected in the application layer) in DDD if no aggregates will ever emerge out of thin air and doing so would cause at least an error in the modeling of the business ?
Long version
There is a popular DDD example which is the e-commerce application consisting of the following aggregates and entities (over simplified)
Modeled as
class Customer {
private CustomerId id;
// related business rules and processes
}
class Order{
private OrderId id;
private List<OrderLine> orderLines;
// related business rules and processes
}
class OrderLine{
private OrderLineId id;
private int quantity;
private ProductId product;
// related business rules and processes
}
class Product{}
// etc...
And it's well established that the creation of the order is done through a factory, usually like:
Order order = orderFactory.createNewOrder(customer);
However I'm arguing that this model is not very clear since I assume the original (made up) requirement is
Customers can place orders.
So doesn't it make more sense to delegate the creation of the order to the Customer aggregate and have the code more verbose ? i.e:
Order order = customer.placeOrder(...);
// Pass the data needed for the creation of the object, or even the factory service if the creation is complex
In my opinion, expanding this view would result in that the actors of the system would be aggregates most of the time and they will contain all the invoking of the use cases (which has the side-effect that the application layer being very thin as well)
Does this second approach violate DDD ? An aggregate being responsible for the creation of another aggregate doesn't feel right but produces better code that -in my opinion- matches the domain better.
Does this second approach violate DDD
No. The patterns described by Evans in the Domain Driven Design book should be understood as "useful ideas that recur" rather than "these patterns are mandatory".
And you will find support in the literature for the idea that, when we are modeling the creation of aggregates, we should be using the domain language, not factories. For example: Don't Create Aggregate Roots (Udi Dahan, 2009).
That said.... when Evans describes the FACTORY pattern in his book, he does so in the context of life cycle management, not modeling. In other words, factories are cousins to repositories and aggregates, not domain entities and value objects.
Shift the responsibility for creating instances of complex objects and AGGREGATES to a separate object, which may itself have no responsibility in the domain model but is still a part of the domain design.
In other words, we might still want to use Customer::placeOrder in our domain model, but to have that method delegate the object assembly to a dedicated factory.
Of course, object creation is not the only place that we use the factory pattern; it can also appear in object reconstitution. A common REPOSITORY pattern is to fetch information from the durable data store, and then pass that information to a FACTORY to arrange that information into the appropriate shape - aka the graph of objects that make up the AGGREGATE.
I understand the factory pattern as an example of information hiding, the factory limits the blast radius when we decide to change how a fixed set of information is assembled into an aggregate.
I would like to understand what's the benefits to create DTO objects when you already have POJO object (as Entity).
In my project I have both :
DTO classes are used to communicate between Web Service and the application
POJO entity classes (JPA) are used for communication between database and the application
If I look at a DTO object class (let's call it MyObjDTO) and the same class but POJO side (let's call it MyObjPOJO) there is no difference at all except MyObjPOJO as annotation due to the fact it's an #Entity.
So in fact, I got in my project 2 classes who look the same (same attributes, same methods) but for different puprose.
IMO, in this case the DTO class is useless and increase application complexity because all I do with DTO class I can do it with my POJO class and moreover, for a single type of object I have to maintain at least 2 classes (the DTO and POJO), for instance if I add an attribute I have to add this attribute in both classes.
I'm not an expert and I'm questionning about my thoughts; what do you think about it ?
This answer is a replica of what can be found on stack exchange. IMHO the OP should be closed for being posted in the wrong forum. It's currently also attracting opinionated answers, though not necessarily so, and isn't tied to java in any particular way.
DTO is a pattern and it is implementation (POJO/POCO) independent. DTO says, since each call to any remote interface is expensive, response to each call should bring as much data as possible. So, if multiple requests are required to bring data for a particular task, data to be brought can be combined in a DTO so that only one request can bring all the required data. Catalog of Patterns of Enterprise Application Architecture has more details.
DTO's are a fundamental concept, not outdated.
What is somewhat outdated is the notion of having DTOs that contain no logic at all, are used only for transmitting data and "mapped" from domain objects before transmission to the client, and there mapped to view models before passing them to the display layer. In simple applications, the domain objects can often be directly reused as DTOs and passed through directly to the display layer, so that there is only one unified data model. For more complex applications you don't want to expose the entire domain model to the client, so a mapping from domain models to DTOs is necessary. Having a separate view model that duplicates the data from the DTOs almost never makes sense.
However, the reason why this notion is outdated rather than just plain wrong is that some (mainly older) frameworks/technologies require it, as their domain and view models are not POJOS and instead tied directly to the framework.
Most notably, Entity Beans in J2EE prior to the EJB 3 standard were not POJOs and instead were proxy objects constructed by the app server - it was simply not possible to send them to the client, so you had no choice about haing a separate DTO layer - it was mandatory.
Although DTO is not an outdated pattern, it is often applied needlessly, which might make it appear outdated.
From Java guru Adam Bien:
The most misused pattern in the Java Enterprise community is the DTO. DTO was clearly defined as a solution for a distribution problem. DTO was meant to be a coarse-grained data container which efficiently transports data between processes (tiers). ~ Adam Bien
From Martin Fowler:
DTOs are called Data Transfer Objects because their whole purpose is to shift data in expensive remote calls. They are part of implementing a coarse grained interface which a remote interface needs for performance. Not just do you not need them in a local context, they are actually harmful both because a coarse-grained API is more difficult to use and because you have to do all the work moving data from your domain or data source layer into the DTOs. ~ Martin Fowler
Here is a Java EE specific example of a common but incorrect use of the DTO pattern. If you're unfamiliar with Java EE, you just need to know the MVC pattern: a "JSF ManagedBean" is a class used by the View, and a "JPA Entity" is the Model in the MVC pattern.
So, for example, say you have a JSF ManagedBean. A common question is whether the bean should hold a reference to a JPA Entity directly, or should it maintain a reference to some intermediary object which is later converted to an Entity. I have heard this intermediary object referred to as a DTO, but if your ManagedBeans and Entities are operating within the same JVM, then there is little benefit to using the DTO pattern.
Futhermore, consider Bean Validation annotations (again, if you're unfamiliar with Java EE, know that Bean Validation is an API for validating data). Your JPA Entities are likely annotated with #NotNull and #Size validations. If you're using a DTO, you'll want to repeat these validations in your DTO so that clients using your remote interface don't need to send a message to find out they've failed basic validation. Imagine all that extra work of copying Bean Validation annotations between your DTO and Entity, but if your View and Entities are operating within the same JVM, there is no need to take on this extra work: just use the Entities.
The Catalog of Patterns of Enterprise Application Architecture provides a concise explanation of DTOs, and here are more references I found illuminating:
HOW TO DEAL WITH J2EE AND DESIGN PATTERNS
How to use DTO in JSF + Spring + Hibernate
Pros and Cons of Data Transfer Objects Martin Fowler's description of DTO
Martin Fowler explains the
problem with DTOs. Apparently they were being misused as early
as 2004
Most of this comes down to Clean Architecture and a focus on separation of concerns
My biggest use-case for the entities is so i don't litter the DTO's with runtime variables or methods that i've added in for convenience (such as display names / values or post-calculated values)
If its a very simple entity then there isn't so much of a big deal about it, but if you're being extremely strict with Clean then there becomes a lot of redundant models (DTO, DBO, Entity)
Its really a preference in how much you want to dedicate to strict Clean architecture
https://medium.com/android-dev-hacks/detailed-guide-on-android-clean-architecture-9eab262a9011
There is an advantage, even if very small, to having a separation of layers in your architecture, and having objects "morph" as they travel through the layers. this decoupling allows you to replace any layer in your software with minimal change, just update the mapping of fields between 2 objects and your all set.
If the 2 objects have the same members...well, then that's what Apache Commons BeanUtils.copyProperties() is for ;)
Other people have already informed you of the benefits of DTO, here I will talk about how to solve the trouble of maintaining one more DTO version object.
I deveploy a library beanKnife to automatically generate a dto. It will create a new class base the original pojo. You can filter the inherited properties, modify existing properties or add new properties. All you need is just writing a configuration class, and the library will do the left things for you. The configuration support inheritance feature, so you can extract the common part to simpify the configuration even more.
Here is the example
#Entity
class Pojo1 {
private int a;
#OneToMany(mappedBy="b")
private List<Pojo2> b;
}
#Entity
class Pojo2 {
private String a;
#ManyToOne()
private Pojo1 b;
}
// Include all properties. By default, nothing is included.
// To change this behaviour, here use a base configuration and all other final configuration will inherit it.
#PropertiesIncludePattern(".*")
// By default, the generated class name is the original class name append with "View",
// This annotation change the behaviour. Now class Pojo1 will generate the class Pojo1Dto
#ViewGenNameMapper("${name}Dto")
class BaseConfiguration {
}
// generate Pojo1Dto, which has a pojo2 info list b instead of pojo2 list
#ViewOf(value = Pojo1.class)
class Pojo1DtoConfiguration extends BaseConfiguration {
private List<Pojo2Info> b;
}
// generate Pojo1Info, which exclude b
#ViewOf(value = Pojo1.class, genName="Pojo1Info", excludes = "b")
class Pojo1InfoConfiguration extends BaseConfiguration {}
// generate Pojo2Dto, which has a pojo1 info b instead of pojo1
#ViewOf(value = Pojo2.class)
class Pojo2DtoConfiguration extends BaseConfiguration {
private Pojo1Info b;
}
// generate Pojo2Info, which exclude b
#ViewOf(value = Pojo2.class, genName="Pojo2Info", excludes = "b")
class Pojo2InfoConfiguration extends BaseConfiguration {}
will generate
class Pojo1Dto {
private int a;
private List<Pojo2Info> b;
}
class Pojo1Info {
private int a;
}
class Pojo2Dto {
private String a;
private Pojo1Info b;
}
class Pojo2Info {
private String a;
}
Then use it like this
Pojo1 pojo1 = ...
Pojo1Dto pojo1Dto = Pojo1Dto.read(pojo1);
Pojo2 pojo2 = ...
Pojo2Dto pojo2Dto = Pojo2Dto.read(pojo2);
I have the following class:
public class DomainClass {
private Integer value;
private Integer total;
private Integer month;
public Double getPercent(){/*Business logic*/}
}
I want to do the same getPercent operation with a list of DomainClass objects without repeat code. I got 2 ideas to handle that but I don't know if they're good ones.
Idea 1 - Create a service and iterate the list:
public class DomainObjectService{
....
public Double getPercent(List<DomainClass> list){
double value, total;
for(DomainClass d : list){
value += d.getValue();
total += d.getTotal();
}
// do percent operation
}
Idea 2 - Query operation at database, fill object and call the business method
public class DomainObjectService{
....
public Double getPercent(){
double value, total;
.... query data with sql and set the above variables
// do percent operation
return new DomainBusiness(value, total).getPercentage();
}
I'm reading that in DDD a entity should handle itself logic but in this case of a collection operation how it should be treated?
Well, if my DDD base knowledge is wrong. I would like to know good article/books/example of DDD in java.
How do you manage your entities? Do you use any kind of ORM?
My solution for this kind of operations is to build a class that manages the collection of object.
So, for example:
public class DomainClasses{
private final List<DomainClass> domainClasses;
....
public Double getPercent(){
// manage the percent operation ...
// ... on all the members the way ...
// ... your business is expected ...
// ... to do it on the collection
return something;
}
// class initialization
}
In this way you can reuse the getPercent code of each class, but also implement a specific version of it to be used by the collection. Moreover, the collection could access to the package private getters, if any, of DomainClass to make this calculations. In this way you expose nothing else than just the functions that you need to build your domain objects.
Note: this solution is viable if you manage your persistence without any ORM. Or, if you want to use it, it will require additional work to configure correctly the container class.
Some links:
https://www.mehdi-khalili.com/orm-anti-patterns-part-4-persistence-domain-model (I work with a DM separated from the PM)
https://softwareengineering.stackexchange.com/questions/371344/why-not-use-an-orm-with-ddd (is what I'm doing, translating the Domain objects to DTOs that will be persisted - it's a bit of extra code to write for collections, but once is tested it works, always, and what you get is a domain that has less no interferences from ORM framework)
Update after question. I use the Memento pattern.
Storing
My Domain Class has a function that export all the data in a Memento object. The repository takes a Domain Instance, asks for the Memento and then:
I generate the SQL insert/update (plain SQL with transaction management from Spring)
You can load your JPA entity and update with the Memento information (care should be taken, but if you write tests, once done it will work always - hence, tests are important ;) )
Reading
For the reverse, building a Domain instance from the saved data, I do this:
in the persistence layer, where the repository code is implemented, I've extended my Memento (lets call it PersistedMemento)
when I've to load something, I build a PersistedMemento and I use it to build an instance of the Domain Class
my Domain Class has a function that allows to build objects from a Memento. Note: this could not always be necessary, but in my case the main constructor ha extra checks that cannot be done when the object is rebuilt from a saved one. Anyway, this simplifies the rebuilding of the Domain class.
To protect the Domain classes from being used outside the world of the domain:
my repositories require an existent transaction, so they cannot be directly used anywhere in the code
the Memento classes have protected constructors, so they are usable only in the Domain package or the Repository package. The PersistedMemento is also hidden in the Repository package, so no instances could be created.
Notes
Of course is not the perfect solution. The Domain Class has 2 functions that are there to support a non domain requirement. The Memento class could also be sub-classed, and an instance could be used to build the Domain Class (but why? It's much more simpler to build it with the default constructor). But, except this small amount of pollution, the domain stays really clean and I can really concentrate on the domain requirement, without thinking how to manage the persistence.
I have inherited an application written in Java that uses JPA to access a database. The application uses an design pattern that I haven't come across before and I would really appricate some guidance on why this pattern is used. Like many applications, we have a front end, middleware, and back end database. The database is accessed via DAOs. Each method on the DAO loads a entity-DTO which is just a POJO with nothing but getters and setters and that entity-DTO is then passed into a entity-proper that has other methods that change the entity state. An example [class names changed to protect the inocent]
enum Gender
{
Male,
Female
}
class PersonDTO
{
private String mFirstName;
private String mLastName;
private Gender mGender;
...
String getFirstName() { return this.mFirstName; }
String setFirstName(String name) { this.mFirstName = name; }
// etc
}
class Person
{
PersonDTO mDTO;
Person(PersonDTO dto)
{
mDTO = dto;
}
String getFirstName() { return mDTO.getFirstName() }
String setFirstName(String name) { mDTO.setFirstName(name); }
// and so on
void marry( Person aNotherPerson )
{
if( this.getGender()==Gender.Female &&
aNotherPerson.getGender()==Gender.Male)
{
this.setLastName( aNotherPerson.getLastName() );
}
aNotherPerson.marry( this );
}
}
This is repeated across 30 or so entity classes, doubled to 60 with the DTOs, and I just cant get my head around why. I understand (bits) about seperation of converns and I also understand (bits) about the difference between an EAO based design to say an active record based design.
But does it really have to go this far? Should there always be at least one "DB" object that contains nothing but getters and setters that map to the DB fields?
Disclaimer: there are varying opinions on this subject and depending on your system's architecture you might not have a choice.
With that said... I've seen this pattern implemented before, not a huge fan of it, in my opinion is duplicates large amounts of code without adding any real value. It seems to be particularly popular in systems with XML APIs like SOAP where it might be difficult to map XML structure directly to your object structure. In your particular case it seems to be even worse because on top of duplicate getFirstName()/getLastName() methods, there is business logic (which belongs in the service layer) coded right into a pojo (which should be a simple data transfer object like the DTO). Why should the pojo know that only people of opposite sex can get married?
To help better understand why, can you explain where these DTOs come from? Is there a front-end submitting data to a controller which then converts it to a DTO, which is then used to populate your entity-proper with data?
It could also be that they are using this just to separate the JPA annotations from the rich domain object.
So I'm guessing that somebody didn't like having JPA annotations and the rich domain object behaviour in one class. Somebody could have also argued that the JPA annotation and the rich domain object should not be in the same layer (because the annotations mixes the concerns) so you would get this kind of separation if you won this argument.
Another place where you'd see this kind of thing happening is when you want to abstract similar annotations away from the rich domain objects (like jaxb annotations in web services for example).
So the intent might be that the DTO serves as sort of the serialization mechanism from code to the database, which is very similar to the intent mentioned here by martin fowler.
This doesn't appear to be a known pattern.
In general
it is common to maintain a separate object to represent the record in the database, referred to as domain object.
the CRUD operations on the object are part of a DAO class and other business operations would be part of a Manager class, but none of these classes store the domain object as a member variable, i.e. neither DAO nor Manager carry state. They are just processing elements working on domain objects passed in as parameters.
a DTO is used for communication between the front-end and back-end to render data from DB or to accept input from end-user
DTOs are transformed to Domain objects by Manager class, where validations and modifications are performed per business rules. Such domain objects are persisted in the DB using DAO class.
I have worked on one project where we have DTOs for the sole purpose of transferring information from front-end controller to some facade layer. Then facade layer is responsible for converting these DTOs to domain objects.
The idea behind this layering is to decouple front-end (view) from domain. Sometimes DTOs can contain multiple domain objects for aggregated view. But domain layer always presents clean, reusable, cacheable(if required) objects.