DDD - Why do we need factories? - java

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.

Related

What's the point of having DTO object when you have the same object as POJO (Entity)?

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);

Best practices with a domain object collection in DDD

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.

DDD When should I create a domain object and a persistence object instead of using a persistence object as a domain object?

As I work with my understanding of Domain Driven Design I find I have a rule that seems to work, though I would like to see if it is overkill and also would like to see other perspectives of the same situation.
My question is this: "When should the domain model and persistence model be contained in separate objects?"
My language of choice is Java at the moment and I am using Spring Data's repository model.
I see three main answers to my question.
Always use separate domain objects from persistence objects.
Use separate domain objects only when putting domain methods (behaviors) on persistence objects is not practical.
Use persistence objects as domain objects in all cases.
In order to ask questions about DDD I find that I have to use an example bounded context since I don't yet know enough about DDD to ask in a more abstract way.
Here is my illustrative bounded context: say I have a law codification system with the following business rules:
Each law on the books must be classified.
Each law has an identifier with two parts, a codification number prefix and a codification coassign suffix. (Example: 100-0100, 599-2030).
There are multiple legal jurisdictions that are using the law codification system and they should be able to make their own coassigns but the codification prefixes are global and must be the same across all jurisdictions to facilitate general comparability.
the codification number prefixes are grouped into broad codification categories. Codification categories have a number range, such as 100-199, 200-299, 700-799, etc.
To express this bounded context as a persistence model I have the following:
table: codification
fields: chart_code, prefix, coassign, codification_category
table: codification_chart
fields: chart_code, jurisdiction_description
table: codification_category
fields: category, low_category_number, high_category_number, description
table: global_codification
fields: prefix, coassign, codification_category
I know, I should be starting from the domain model first. I have a persistence model and a domain model
In my domain model I have three domain objects
public Codification {
private String prefix, coassign;
codificationCategory codificationCaegory; // an enum type
public Codification(...) { // set private vars }
// getters for private variables
}
public CodificationChart {
private List<Codification> chartCodifications = new ArrayList<>();
private String chartCode;
// public constructor to initialize private variables
// getters for private variables
public Codification addCodificationToChart(Codification){...}
public void removeCodificationFromChart(Codification){...}
public boolean checkCodificationInChart(Codification){...}
}
public enum CodificationCategory {
CIVIL, CRIMINAL, PROPERTY, CORPORATE, FAMILY, CONSUMER, ETHICS, BANKRUPTCY;
}
ORM Objects:
JPA Mappings of the tables mentioned earlier with the "Entity" suffix added to their table names.
They are omitted for brevity.
Each one contains getters and setters like JPA Pojos do.
If someone asks for the Persistence objects code I will post it.
The only point at which my domain objects know about the persistence model is in my factory object CodificationChartFactory, which has the repository interfaces I am using to interact with the ORM objects mentioned earlier. This factory is the only part of the domain that uses the persistence repositories, thus the only part that interacts with the persistence layer.
Is creating a separate domain model here wasteful effort?
I can see how it is possible for me to put my CodificationChart behaviors on a Persistence object. It just somehow feels wrong to put those behaviors on a persistence object who's only job is to retrieve a record from the database.
I definitely stand to be corrected.
Both approaches are correct and are a matter of taste from a design point of view. Some people don't want their domain object to have absolutely anything to do with persistence and do create an extra layer of Entity objects... some people don't think this is a major problem and are happy to go ahead and use the domain objects as the persistence objects.
Personally (and subjectively), I think that using JPA and have an extra layer of Entity objects is the wrong approach. The aim of ORMs like Hibernate is to be a bridge between Object and Relational models (I know it's in the name :). I think a way better approach, in the case one wants to keep things separated, is to use something like mybatis or plain SQL, but definitely not JPA... otherwise it's just adding complexity for the sake of complexity (JPA is not the easiest framework to learn)
I'm happy to live with the mix and annotate my domain objects. As I know it makes the persistence easier to manage... but at the same time, I feel very comfortable with Hibernate/JPA and been using it for 10 years :).
I had a very similar question 3 years ago, which I posted on programmers site - Do ORMs enable the creation of rich domain models?

DTO objects for each entity

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.

Naming convention when using hibernate

Me and my team are building java EE app as a school project and we've decided to use hibernate. We also want to make the whole project as nice and clean as possible, so we're trying to follow recommended conventions. Nevertheless I wasn't able to find out, what are the conventions for hibernate files.
I.E. I've got a folder /cz/fit/cvut/nameofmyproject/ and there I've got packages controllers, models, utils. In controllers I've got Spring controllers, in models I want to have models for my entities and in utils I've got SessionFactory for hibernate. And now my question:
How shall I name classes in model package? Should it be MyEntityNameDTO, or did I misunderstand the meaning of the DTO and should I just name them MyEntityNameModel? And what should be the proper name for the folder for my DAO classes? Will this simple division be enough for a middle-size project (max ~20 classes/folder) or would it be too confusing? Thanks for any tips from praxis :)
DTO stands for Data Transfer Object. A DTO is a class which is more a data structure than a real class, usually, and which is created to transfer information from one layer to another, often across the network. It's not a model entity.
A DTO is often used
when serializing real model objects is not paractical (because the structure doesn't fit, or because the receiver doesn't have access to Hibernate classes, or because lazy-loaded entities are a problem)
when you want to transfer information that is an aggregation, or a complex view, over your model objects (like data of a statistical report for example)
So naming your entities DTO is not a good idea. DTOs and entities are different things. The Model suffix is also cumbersome. Entities are usually named after what they represent: Customer, Company, Player, Order, etc.
Segregating classes based on their technical role is an often used solution. But it tends not to scale when the application grows. I usually have a first level of segregation based on a functional aspect (like customer management, order management, security, etc.), and then a second level based on technical aspects (service, dao, model, etc.)
UserDAO - interface
UserDAOImpl - implements UserDAO
That is generally what I use. Sometimes the Default prefix like DefaultUserDAO might make more sense if you're creating an interface that you expect others to implement but you're providing the reference implementation.
Most of the time I feel those two can be used interchangeably but in some situations one provides a little more clarity than the other.
There are two conventions that I've seen:
FooDao for the interface and FooDaoImpl for the implementation
IFooDao for the interface and FooDao for the implementation
The former has its roots in CORBA; the latter is a Microsoft COM/.NET convention. (Thanks to Pascal for the correction.)
Hibernate provides the Naming Strategy interface to be implemented by the implementation.
I am listing here few methods.
String classToTableName(String className) – should return the table name for an entity class.
String columnName(String columnName) – handle to alter the column name specified in the mapping document.
String tableName(String tableName) – handle to alter the column name specified in the mapping document.
String propertyToColumnName(String propertyName) – handle to map property name to column name.

Categories