uladzimir
uladzimir

Reputation: 5689

Using private fields in the grails controller

I know that service in grails is singleton by default.

Is it bad practice to use private fields in controller/service? Could anyone explain, why?

Upvotes: 0

Views: 163

Answers (1)

Joshua Moore
Joshua Moore

Reputation: 24776

Controllers are not singletons by default. They are created for each request. Services are, by default singletons. It's not bad practice to use private fields in Services. It's fairly common that Services have private fields to hold configuration state at runtime.

I suspect your concern is about using private fields as a means of storing state for a particular request within a Service. Which is obviously bad considering there could be N requests being serviced by the Service. So long as you are using private fields to control the service from an application perspective and not a request perspective you will be fine.

Edit (further information) As stated, services can and often do have private members. However, you should never use these as a means for storing information about the current request being processed. Obviously, since this is a singleton that would cause interleaving issues. Only use private members to store information that is visible across all requests. Typically these will be configuration settings of the service itself.

It's best to make your service stateless in regards to the requests they are processing. Any state you need should be encapsulated in the parameter(s) or input/output of your Service methods. Services should act on data, not the other way around.

Upvotes: 3

Related Questions