While reading "The Definitive Guide To Grails", I am a little confused as to Command Objects. They seem to be a wrapper around domain classes to assist with validation but that is functionality already available in domain classes via built in constraints and further via custom validators so then what does a command object do really and what motivates us to need it?
The book starts the discussion on command objects by stating that
"Sometimes a particular action doesn’t require the involvement of a domain class but still requires the validation of user input."
However, then it demonstrates the declaration of and the usage of a command object with regards to an Album
domain class. So, it seems whatever a command object does is still closely related to domain classes. I'm sure my confusion is completely a result of my lack of understanding and so I wish to seek any clarification. Thanks.
They seem to be a wrapper around domain classes...
You can use command objects that way, but that isn't their primary use.
Command objects are useful when you want to encapsulate a group of request parameters and do something with them together. That something might or might not have anything to do with domain classes.
For example, you could have a Grails app which doesn't have any domain classes at all and command objects could still be really helpful. Imagine a Grails app that is just a service layer that receives request from web forms or REST requests with a JSON body or whatever and the Grails app is going to receive those requests, validate the inputs, maybe do some math or anything at all and then make a REST call to some other backend process that might store them in a database or generate reports or whatever. In a situation like that, there are a lot of reasons that you might want to use command objects even though no domain classes are involved at all.
Don't get bound up thinking that command objects have to be tied to domain classes. Sometimes they are, but don't limit your thinking of them to that context. Use command objects when you want to relate a group of request parameters together and do something with them.
I tend to use command objects that match what is happening in the UI layer, form submits can be validated with command objects then passed into services that do the work of persisting them. It many times makes sense to have your domain model be different then the UI flow you are working with.
My domain layer may also have looser constraints than some of the command objects if I want to require certain flows provide enough information.
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