Friday, July 4, 2008

Struts 2 anemic domain models with POJOs

The other day I was integrating Easydealer.net PHP code and Java modules. The goal is to gradually move most Easydealer core code to Java (Struts 2, Spring, Hibernate). But since there is a lot of legacy code written in PHP we must be able to code some stuff also in PHP.

Since the browser is the user interface we had a simple solution - make two logins and create user sessions with Java and PHP backends with one login form. Then we can decide with any click if we want to code it in Java or PHP. No problem - said, done (with Iframe btw.).

Now I was modifying the same database tables with Java and PHP. In PHP we use PEAR_DB for databse abstraction and PEAR_DB has its own sequence schema for primary keys. It keeps the last sequence number for a table in a little table named "tablename_seq". Now if I needed to insert data from Struts I had to generate the primary key with the same schema as PEAR_DB . OK. No problem here, we just code it in our service layer.

But wait! That way I'll have to specifically code it for all the tables I am inserting in all the service classes that deal with database insert/update. That sucks. Should'nt all the domain classes just "know" about their primary keys? It makes no sence for the service layer to tell the domain classes about their identity. This code should be in our domain model!

So alternatively I could program the code that deals with PEAR_DB "_seq" tables in getters/setters of the domain model classes. And that brings us to the subject. The simplest struts 2 domain model objects contain fieldnames, getters/setters and some annotations for relations. But all that information can be as well described in a list or map . In our PHP code all the database model is described in one big array. Ok some getters/setters have a little business logic in them. But that's it. So i have ended up with an anemic domain model, wich is basically a description of my database structure in POJO-s. That's not my goal!

While searching for alternatives I found this little gem . It is a bit dated, but there are practically all the alternatives analysed. And the conclusion should be - pick your poison :) .

No comments:

Post a Comment