This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes OO, Patterns, UML and Refactoring and the fly likes Somewhere along the lines of Anemic Domain Model Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » OO, Patterns, UML and Refactoring
Bookmark "Somewhere along the lines of Anemic Domain Model" Watch "Somewhere along the lines of Anemic Domain Model" New topic
Author

Somewhere along the lines of Anemic Domain Model

Udayan Patel
Ranch Hand

Joined: Oct 14, 2004
Posts: 94
Fowler�s Anemic Domain Model

His quote:
I don't know why this anti-pattern is so common. I suspect it's due to many people who haven't really worked with a proper domain model, particularly if they come from a data background. Some technologies encourage it; such as J2EE's Entity Beans which is one of the reasons I prefer POJO domain models.

His argument is totally based on how you analyze problem and how you draw boundary between application and persistence. Back from early days of C++ world it makes perfect sense! well no, From pure OOA&D point of view it makes perfect sense.

For example if you have a file that you are reading: (I chose this particular example because I recently worked on this and first thing came to mind)

Two possible scenarios:
1.Analyze structure of the file
2.Analyze data inside the file.

Analyze Structure of the File:
File has records (lines)
Lines has fields (tokens delimited by some character)
May be some special types of records. (to describe certain pieces of file).

So, In this case you will end up creating:
MyFile:
ArrayList records; //list of MyRecord
Read();

MyRecord
HashMap Fields; //list of MyField
getFieldByName(name);
addField(name, MyField);
parseRecord(String line);

MyField
Name;
Value;
//May be some more properties
So, In this case service layer doesn�t have much as he said can be kept thin. And you can put behavior in domain model here. Logic is scattered, and you must need to know the contract of each object.





Analyze Data:
Let say file contains financial information like, Borrower information, financial data for a borrower and such.

Therefore you will come up with:

Borrower
String Name;
String ssn;
Date dob;
Address address;
//getters and setters
Note here, Borrower doesn�t have behavior. But When Borrower becomes �user� of the System, It does have behavior. In that case, you will have User with role of borrower. And borrower becomes more significant as borrower is an actor of the system and would contain certain extra set of properties.

Finance:
Float principle;
Float interest;
Float interestRate;
//and such
// getters and setters

Simply no behavior under any circumstances. (His argument)

Now, for your service layer you have algorithms to parse file. And parse each line on file. Logic is straight forward to find and understand as you will be executing something like
FileParserFactory factory = FileParserFactory.getInstance();
FileParser parser = factory.getParser(fileType);
parser.parse(file);

If you think in terms of data persistence, you will end up with 2nd part, which is nothing but DTO. Where, as if you think in terms of Application you will end up with first approach. Which is good but it still would require DTO at certain point (well different kind though something like Field underneath for data mappings. In my understanding, Application doesn�t need to know how the data is analyzed or rather organized in catalog particularly while executing business situation. Application should be more focused on how to operate on data.

If I am working on any kind of infrastructure projects I would go though first route. If I am writing something that has nothing to do with infrastructure projects, probably something like ordering system which doesn�t even care for inventory, where you receive data and pass it off to persistence after simple validation. I would simply put bunch of value objects (java beans, DTO call it whatever you want), Being operated by a service layer and pass it off to persistence. Where as infrastructure projects involves different types of clients including fulfillment systems, in this case I would like to draw clear boundaries between contracts of service layer and domain model and persistence. Certainly, I still would need value objects to pass of the data that was operated by domain model as I definitely don�t want any parts of my persistence to know any type of behavior for an object.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I associate anemic models with stateless servers. We did a fat client app with an elaborate model of objects with rich behavior. They encapsulated state and behavior and stayed around for the life of a business function or a user session, interacting in interesting ways.

We migrated the very same domain problem to a stateless server. Now we wound up with a layer of objects that represent data structures (often one table, sometimes more complex) and a layer of objects with all the behavior but no internal state. There really isn't an object model here, just behvaior-free structures and data-free behavior. This could be done in C or COBOL.

Never mind which one provided better business value for the dollar (anemic is only an anti-pattern if it doesn't work) the former was much more rewarding for an OO geek.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Udayan, I'm not sure I follow the distinction you make.

I recently worked on a custom module for our product that was basically a CRUD application - not much more than a complex Swing form for a medium complex data model (a dozen tables).

We used Hybernate as the persistence layer, and a product (Hybernate Synchronizer) that automatically creates java beans from the database mapping. Those beans are, of course, without any behaviour.

There was a little bit of business logic involved, though - some fields automatically updated when other fields where changed and such things. Nothing complicated, either.

Now we had to possible ways to implement that: let the beans alone and implement the logic in some layer above them, or put the logic into the beans themselfes. We did the latter, and I think it considerably simplified the design.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Udayan Patel
Ranch Hand

Joined: Oct 14, 2004
Posts: 94
Originally posted by Ilja Preuss:
Udayan, I'm not sure I follow the distinction you make.

I recently worked on a custom module for our product that was basically a CRUD application - not much more than a complex Swing form for a medium complex data model (a dozen tables).

We used Hybernate as the persistence layer, and a product (Hybernate Synchronizer) that automatically creates java beans from the database mapping. Those beans are, of course, without any behaviour.

There was a little bit of business logic involved, though - some fields automatically updated when other fields where changed and such things. Nothing complicated, either.

Now we had to possible ways to implement that: let the beans alone and implement the logic in some layer above them, or put the logic into the beans themselfes. We did the latter, and I think it considerably simplified the design.


Sorry took me little longer to reply. I belive that you understand that you will need DTO (beans) no matter what. Lets use your application as an example. If I were to work on that application, I would have gone first route. But my layer that includes business logic would have very abstract algorithms that would includes the core business activities. What I mean by core business activities is, Consider that it was a retail application. Core activities for that would be like Invoice, Purchase order and such, I would have designed my objects as such that It know how to create invoice based on given purchase order(DTO) or how to create purchase order based on provided data. let PO has an invoice (another DTO may be!) attached to it after its created.

What this would buy me?
If I have two different types of customer I can simply laydown strategy and interchange my alogrithm for each types. As you mentioned, It was a swing app(making an assumtion here that swing thick client was later made stand alone client to core application running somewhere else), I am sure if you were to add a web client to it, this route would save you lot of time. all you will be doing is just the front end part. By the time your web client's request to a specific taks gets its response back, all it is getting back is DTO. therefore clear boundries between UI, middleware(businessware call it whatever you call it) and persistence. defines clear contract of each layer and within each layer defines clear contracts of each object. So rather than have customer.doOrder() or order.doOrder(), I would prefer PurchaseOrderCreator c = new PurchaseOrderCreator(customer); // service layer gets hold of my application layer
c.doOrder(customer, OrderDTO); //application layer executing core business logic. and gets hold of persistence and let it finish its job. BTW you might want to reconsider creating serialiable objects(assuming that your beans impliments serializable) with business logic in it.
[ December 29, 2004: Message edited by: Udayan Patel ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
DTO are necessary when you really need the T: transfer between components. The boundary between OO and Relational or other data stores might be among the necssary places. In a stateful system, say a Swing fat client, I'd try to hide the existence of those DTOs within a persistence framework and write the rest of the system with a rich (seeking an opposite for anemic) object model.

If I have DTOs everywhere, I'll get methods like:

With a rich model I might have


Anemic models separate the behavior from the data because the DTOs by definition have no behavior. This is a perfectly valid way to build software and might be a good choice for a stateless web server, but it's "not very OO" in flavor. Rich models encapsulate behavior and data together, much more in the spirit of "good" OO. (I put "good" in quotes because if I venture any definition of "good" we'll be here all night debating it. Maybe we don't have to do that again.)

My 2 cents.
 
wood burning stoves
 
subject: Somewhere along the lines of Anemic Domain Model
 
Similar Threads
JEE5 still pushes for anemic domain model ?
Java EE 5 and JPA design issue about how much logic do use in entities?
Class diagrams
Domain Layer dependancy confussion
Grails best practices