Separating Domain Model and Application Model

Warning: Illegal string offset 'language' in /var/www/vhosts/ on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ on line 513

Let’s take a simple retail app as an example. The app has the following (partial) domain model:

It can be quite tempting to use a domain model as an application model (as in the “M” in MVC). Your application obviously needs to use the data presented in the domain model. At first, it may seem logical to access this data directly, e.g. for showing a product name on a product details page. There are several problems with this approach though.

The domain model may be too verbose for your application’s needs. Let’s say you don’t care about the image details, but only want the URL. The app may also want to check to see if a product has an image associated with it before trying to display it. To solve this, the Product and Image objects above can be combined into one, like below.

Another benefit is that you keep things DRY. The validation logic is not repeated in various classes (think different Presenters in the MVP pattern).

To facilitate the conversion from domain model to app model, you could introduce a converter class. Something like the below.

  1. public class ModelConverter {
  2.     public AppProduct convertProduct(DomainProduct product) {
  3.         // Imagine a nice implementation here...
  4.         return appProduct;
  5.     }
  6. }

During conversion you can also do some more data validation to make sure your app doesn’t break when back-end data is incomplete. In this example, for instance, you shouldn’t rely on the image always being populated in the Product object.

All in all, separating your domain model from your application model will help you build a more stable app, trim data floating around and reduce code duplication (by centralising data validation).

Leave a Reply

Your email address will not be published. Required fields are marked *