Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shouldn't Grails GORM calls be in the service and not controller layer?

Tags:

grails

I'm trying to decide, according to Grails best practices and MVC patterns, when is the correct time to introduce a Service and not keep fattening controllers. I find it somewhat conflicting, what I've read about best practices and what appears to be common practice, so would love to hear what others think about this.

With GORM calls in mind, I would have expected that anything to do with GORM should really go into a service. Although I don't practice this myself, especially when writing very basic controller methods like show that simply perform a get() on a domain class and then render a view to show the details of the retrieved object.

However, after following books like 'Clean Code' and similar books, well maintained code should be cohesive and methods should ideally perform a single task only. So in the perfect world, would the show method in a controller be responsible only for determining the object to display before rendering a view? The retrieval from the database could go into a method in the database that's sole task is to retrieve from the DB and throw an exception if not found etc.

But yes, this does somewhat seem like overkill.

So taking the step a bit further, the create() or update() methods. Again currently Grails' generated code puts everything into the controller, no use of a service at all.

So when would the recommended point be that we need to use a Service? Is it only when something transactional has to take place, for instance, on a create() call, we might also want to write a record to a Log file to keep an audit log of sorts. Surely this warrants a service?

I'd love to hear what others feel is the correct time to introduce services, I imagine it differs greatly person to person.

like image 493
David Brown Avatar asked Aug 24 '12 13:08

David Brown


2 Answers

I recommend you this post: http://www.infoq.com/articles/grails-best-practices

like image 119
Roberto Perez Alcolea Avatar answered Oct 24 '22 04:10

Roberto Perez Alcolea


We are creating static methods in Domain class to encapsulate queries. Service are used only for transactional operations or very complex queries with multiple domains interaction. Controllers simply call domains or services methods.

like image 34
AA. Avatar answered Oct 24 '22 03:10

AA.