What logic should go in the domain class and what should go in a service in Grails?
grails, oop
Solution
In general, the main guideline I follow is:
If a chunk of logic relates to more than one domain class, put it in a service, otherwise it goes in the domain class.
Without more details about what sort of logic you are dealing with, it's hard to go much deeper than that, but here's a few more general thoughts:
- For things that relate to view presentation, those go in tag libs (or perhaps services)
- For things that deal with figuring out what to send to a view and what view to send it to, that goes in the controllers (or perhaps services)
- For things that talk to external entities (ie. the file system, queues, etc.), those go in services
In general, I tend to err on the side of having too many services than having things too lumped together. In the end, it's all about what makes the most sense to you and how you think about the code and how you want to maintain it.
The one thing I would look out for, however, is that there's probably a high level of code duplication in what you are porting over. With Grails being built on Groovy and having access to more powerful programming methods like Closures, it's likely that you can clean up and simplify much of your code.
Problem
I am working on my first Grails application, which involves porting over an old struts web appliction. There is a lot of existing functionality, and as I move things over I'm having a really hard time deciding what should go in a service and what should be included directly on the model? Coming from a background of mostly Ruby on Rails development I feel strongly inclined to put almost everything in the domain class that it's related to. But, with an application as large as the one I'm porting, some classes will end up being thousands upon thousands of lines long. How do you decide what should go in the domain versus what should go in a service? Are there any established best practices? I've done some looking around, but most people just seem to acknowledge the issue.