views:

417

answers:

3

Documentation says:

The Grails team discourages the embedding of core application logic inside controllers, as it does not promote re-use and a clean separation of concerns.

I have one API controller and a few Groovy classes in src/groovy folder. Those classes just implements my application logic so actions in API controller works in this way:

//index page
def index = {
    render new IndexApi().index(params) as JSON
}

I'm curious - is there any reason to move my application logic from plain groovy classes into services ?

+3  A: 

If you want transactional behavior you should put your logic in the Services. Else you would have to take care about it yourself, which is not in the spirit of using Grails.

Being not a grails expert myself, I put my 'not transactional' classes outside the service layer, like builder classes, helpers, and other logic that is not transactional but used from the service layer.

HeDinges
+2  A: 

There are three reasons:

  1. It makes the controller smaller -> easier to understand and maintain

  2. It makes you logic easier to test.

  3. You really don't want to manage your transactions manually.

If you would put everything in the controller, you would need to create the Web runtime to be able to run any test. If your logic is outside, you can copy the data you need from the HTTP request and all the other sources and just call the code. So the logic isn't depending on HTTP sessions, requests or anything else you don't want to.

For example, to test JSPs, you need a HTTPRequest. For a request, you need a HTTPSession and a JSPWriter. Those need a session context. So just to be able to run a single test, you need to set up and initialize a whole bunch of classes. And all of those are interfaces and the implementations are private. So you must implement the actual methods (all 300 of them) yourself. And you better get this right or your tests won't test what you want.

Aaron Digulla
+3  A: 

Actually services are not just about transactions. Services are great for zero-config injectable singleton components, and they can can be reloaded without restarting the whole grails environment, AND they can be discovered as artefacts and hence automatically exposed with remoting plugins.

Marc Palmer