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.
A domain class fulfills the M in the Model View Controller (MVC) pattern and represents a persistent entity that is mapped onto an underlying database table. In Grails a domain is a class that lives in the grails-app/domain directory.
Services in Grails are the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow with redirects and so on.
Go to start.grails.org and use the Grails Application Forge to generate your Grails project. You can choose your project type (Application or Plugin), pick a version of Grails, and choose a Profile - then click "Generate Project" to download a ZIP file. No Grails installation necessary!
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With