Why do I care about pluggable persistence? Macromedia Flash Tool “Zorn” to Run on Eclipse
Jun 07

Model talking to Service Layer: Good practice or bad?

Java, Tech Add comments

In general I am a fan of OO practices, and giving as much behaviour as possible to my object model. Of course, this is within reason, and I only want my model to have the logic that makes sense for the given objects.

However, I often find that a lot changes when I see model’s that are used on the web tier.

I often run across this pattern:

  • Action talks to Service layer which returns dumb model objects
  • Model objects are placed in the request
  • View generates page, using the model

Since the model contains simple properties, with the odd piece of simple logic, and relationships, if a page (view) needs to get more information, it either:

  • Runs another action, which in turn talks to the service layer again to get the new info
  • The original action has multiple calls to the service layer

I actually prefer a different way of doing things. I want the dumb model smarter. I want to do real object design, and have rich behaviour in the model. In fact, I sometimes take it so far that my userSession object can traverse to most pieces of data as needed, but that is another matter.

What does this all mean? Imagine that I have a core model object that I return, and I want the object to have a method: Collection getAssociatedActivities().

What does this method do? Well, it could simply be walking our in-memory data, doing a lot of munging and calculations to work out the association based on rules.

However, this may not be enough. Maybe a complicated query needs to be done to work this out. Rather than using a Comparator and sorting through the model, and doing a bunch of aggregations, I want to let the database do what a database is good at.

This means that the implementation of this method changes from:

public Collection getAssociatedActivities() {
// sort through data model, using a lot of Comparators, making sure the data is all loaded, etc etc.

// 50 lines later...
return theAssociatedActivities;
}

to something like:

public Collection getAssociatedActivities() {
SomeService service = getSomeService(); // injected, via a BeanLookup, or what have you

return service.calculateAssociatedActivities(); // in here the services tier talks to the data tier to do a lot of the work
}

Implementation Encapsulation for Performance

What I like about tweaking the implementation of this method, is the fact that it is all encapsulated. At first I can put it in code directly. If it needs to go back to the service tier based on:

  • Performance: Turns out the DB can do this a lot faster
  • Cleanliness: Nicer to be shared at that tier

it can simply be done.

Choosing in the web tier

Compare this to an approach I see all the time, in which the web tier decides what value objects it wants back. In this case, when the interface needs to change to hit the services tier, either:

  • The main Action hits the services tier again to grab the associated activies object and plugs it in the request
  • The view does a pull which hits another Action, responsible to hitting the services tier and getting the associated objects

Any which way, you end up changing a lot, just for this issue. The web tier is totally changed for performance reasons. The rich object model is compromised, taking functionality out, for performance reasons.

Conclusion

I like rich models, and I like hidding as much as possible underneath. This allows me to change the engine under the hood without bugging the folks on the web tier. Thoughts?

Note: Cameron had some interesting things to say about Protecting the Domain Model

22 Responses to “Model talking to Service Layer: Good practice or bad?”

  1. Eelco Says:

    This is the nbr 1. reason why I switched to Wicket. I too like my models rich and object oriented. And I like freedom in how I /structure/ my application instead of being forced into using hacks all over the place (like chaining commands) just to make things work.

    I am active for Wicket so you could consider this a plug, but to my defense, I am not the original author and found Wicket only after a desperate search of how to break out of problems you described above :)

  2. zany Says:

    Is the service layer the model layer? I am confused by that. You have the web layer that talks to the service layer, don’t you?

  3. Me Says:

    Doing this means your model objects aren’t serializable so you can’t put them in session or send them to a client.

    Is it worth it?

  4. Michael Koziarski Says:

    IMNSHO you’ve got it exactly right Dion.

    Your UI shouldn’t be touching this ’service layer’ stuff at *all*, your OO code (model layer, PD layer, business logic layer) should be all it’s aware of. The fact that one method on your classes is handled by the service layer, and another by the classes itself should be completely hidden from the UI.

    One suggestion, calling the method getAssociatedActivities implies it’s a simple getter. Typically I call this kind of thing listAssociatedActivities to give the hint that you can’t call this 123897 times without taking a hit.

  5. Eelco Says:

    The question that pops up when talking about service layers is whether one plans to implement everything that smells like doing something with your domain model as service. Imo, that is not a good thing, as you will end up having an enormous monolitic service layer, where half of the services are there for the web layer only – even though those call are made through your business objects.

    I prefer to have a small service layer, and put anything that is specific for the web layer in decorators.

    getAssociatedActivities looks like a method that is enough to-the-point to want to have in your model object itself. However, methods that do e.g. a specific sorting, or combine several properties to output a UI string are candidates for putting in a decorator.

  6. Anssi Says:

    In a non-distributed Web application I would do it like you described it. Hibernate would be able to lazily load those associated entities so that the model objects are not aware of the “services” or anything that is persistence related. Additionally it caches the associated entities so that repeated calls within one hibernate session don’t hit the database.

    I think it is perfectly OK that the domain model objects are talking to different infrastructure related services. These services could be related to persistence, e-mail sending, JMS or whatever.

    But in a distributed environment these service calls are problematic. The Web tier may be behind a firewall that prevents DB access and therefore those services cannot be used. Therefore some of the methods in the model classes become unusable if the domain objects are transferred over the wire and usen in the Web tier.

  7. Rickard Says:

    I agree, and blogged about how to implement this using AOP some time ago:
    http://jroller.com/page/rickard/20050502

  8. Anonymous Says:

    This is one of the things I really like about ActiveRecord, (part of Ruby on Rails), all my Models are smart and don’t need to talk to some service layer

  9. Daniel Miller Says:

    It seems like you’re asking for a way to use complex logic to define a relationship between your model objects (currently that’s only possible in the service layer, but we shouldn’t have to do it that way).

    That’s essentially what I was asking for in my comment to this blog post: http://blog.hibernate.org/cgi-bin/blosxom.cgi/2004/08/10#v3-filters. The response to my comment went something like “your idea is just plain WRONG because your example had a method called “getSomething” with an argument and getters NEVER have arguments” (my followup was ignored). Sorry for the rant, but sometimes those guys have no patience at all. Anyway, in my comment I was really asking for a way to have methods on a model object do things that can only be done by a service.

  10. Rodolfo Says:

    Hello Dion,

    Just curious: can you explain why a so smart UserSession object is a good example of OO design ?

    I agree we can call services from domain objects. This is very natural for me since usually I try to put services inside my domain objects.

    What is a service ? A Web Service ? A stateless, secure and transacional component ? A J2EE Application Service pattern instance ? A facade ?

    Frankly, sometimes I think is more easy to cut “layers” from our vocabulary to make easier to visualize domain objects instances working instead of layer approach.

  11. Saint Peter Says:

    Well I often dealt with the problem myself. What I don’t like right now at my applications is that there is a domain model that is AT THE BASE of my class/package hierarchy. Meaning that services, utils, GUI classes, all make use of the domain objects. That means they have a dependency on the domain model.

    What bothers me is that sometimes I would really like to have some more “business” related operations onto the domain model itself. But all the business logic is encapsulated into the services layer and by using a service into the domain model I’d create a cyclic dependency between the services and the domain model and from my point of view that smells.

    This is something I’m thinking to from quite a time, w/o actually having a clear way to solve it …

  12. Jon Tirsen Says:

    In my preferred design for web applications I don’t even have a separate service tier. I may have “service” objects (objects without identity, much state) but in this design they’re really part of the domain.

    Something that bugs me when using Spring though is that it’s hard to inject service objects into entities (objects managed by Hibernate). I usually end up having to resort to service lookup which is kind of annoying. You say “injected, via a BeanLookup, or what have you” which is almost a Fermat-like comment. Would you care to expand on this, Dion? I’m very curious…

    (In fat client apps you have a distribution boundary and are therefor forced to using a service tier.)

  13. levan Says:

    http://filmy-z-shemal.lolek.pl | filmy z shemal | [url]http://filmy-z-shemal.lolek.pl[/url]

  14. penis enlargement pills Says:

    Penis Enlargement Products
    http://www.penis-enlargement-live.com

  15. mescane Says:

    http://www.cho69.com
    http://health-guide.uv.ro
    http://www.mescane.blogspot.com

  16. Lindsay Lohan Says:

    Lindsay Lohan, Lindsay Lohan Pics, Lindsay Lohan Biography, Lindsay Lohan Lyrics,Lindsay Lohan Vanity Fair , lindsay lohan OOPS, Lindsay Lohan Wonder Woman, Lindsay Lohan Tattoos, Lindsay Lohan Music, Lindsay Lohan Hair, Lindsay Lohan Diet, Lindsay Lohan stories, Lindsay Lohan Height, lindsay-lohan-filmography.php, Lindsay Lohan Skinny, Lindsay Lohan Smoking, Lindsay Lohan bra size, Lindsay Lohan Picture, Lindsay Lohan Boyfriend,

  17. Cat Says:

    Cat, Cat families,nformation about cats and kittens Cat health, best way to keep your cat healthyCats behavior, All about Cats behavior Cat picture,yahoo Shopping is the best Crystal Orange Cat PictureCat Sound, Control of Sound Localization in the Cat Cat Name, Name for the Domestic Cat. Category provided on google Cat Home, About Cat. HomeCat Power, Cat Power find on msn EncartaFunny Cat, Do you have a funny Cat Picture Cat Eyes, view the world through the eyes of a catCat Tattoos, Cat Tattoos ShopCat Women,

  18. Cruise Says:

    Cruise, Cruise Dinner, Cruise trip, Princess Cruises, Cruise jobs, Cruise Wear, Cruise Advice, cruise missile, Discover Cruises, Trips tips, Cruise By Interest, Cruise Overview, First time cruisers,

  19. aishwarya rai Says:

    aishwarya rai, Aishwarya Rai Biography,Aishwarya Rai Home,Aishwarya Rai Pictures,Aishwarya Rai Dies,Aishwarya Rai Wallpapers,Aishwarya Rai Forever,Aishwarya Rai Miss World 1994,Aishwarya Rai Latest News,Hot Aishwarya Rai Wallpapers,

  20. Size Genetics Says:

    SizeGenetics is the highest quality penis enlargement device. Expensive, but effective. Especially with prosolution pills or/and penis enlargement exercises. You can deffinetely obtain a permanent penis enlargement, in just 6 months.

  21. Swinger Says:

    Nice site keep up the good work !

    Real Swingers

  22. mosK Says:

    Formulated from herbs from around the world that have been proven to work, you can be assured Vimax will improve your performance http://www.penis-enlargement-dream.com

Leave a Reply

Spam is a pain, I am sorry to have to do this to you, but can you answer the question below?

Q: What are the first four letters in the word British?