Usage of command objects in Grails for updates

1.1k views Asked by At

I read that services are used for updates across multiple domain classes. However, I have command classes, and I would like to know whether putting the logic that makes transactional updates into a command class has a significant downside (or breaks the Grails paradigm). Something like:

class ObjectOneCommand {
...
    def save() {
        objectOneInstance.save()
        objectTwoInstance.save()
    }
}

And in a controller

ObjectOne.withTransaction { transactionStatus ->
    objectOneCommand.save()
}
3

There are 3 answers

0
Ciaran Archer On BEST ANSWER

I'm only new to Grails, but from what I understand, the command object is basically a clever way to do data-binding on incoming parameters so that you can validate them further, or perhaps do some processing on them. Essentially it's taking the domain model constraint checks from the domain class itself and massaging properties before they are passed to a domain object for persistence (often via a service).

Thus command objects (for me anyway) are not a place for transaction business logic on domain objects.

Also since services can be injected into other classes, you can reuse business logic in services in this way. If you place your logic in command objects, dependency injection is not an option for you and you may end up duplicating logic amongst different command objects.

So since you can inject services into your command classes, so I guess it might make sense for you to go down that route.

0
AdamH On

Generally speaking, that's against the Grails paradigm, and also most MVC paradigms. As Ciaran pointed out, logic you put in Command and Controller classes is not re-usable. You won't be able to call it from other controllers (easily), so you'll probably end up re-writing it time and again. Making a method in your service to do this persistence, with def transactional = true would be much better.

0
SGT Grumpy Pants On

Check out this link where there author, David Dawson, suggests using command objects to model incoming requests and to maintain state throughout the duration of a request. I'm not sure if it's a good or a bad idea, but it's very similar to what you're describing.

http://www.simplicityitself.com/article/all-hail-command