Grails Command Objects - What is the Motivation for Them?

As I read The Ultimate Grails Guide, I got a little confused about Command Objects . They seem to be a wrapper for domain classes to help with validation, but is it functionality already available in domain classes through built-in constraints and then through custom validators, and then what really makes the team object and what motivates us to do it?

The book begins a discussion of team objects, indicating that

"Sometimes a specific action does not require the participation of a domain class, but still requires verification of user input."

However, it then demonstrates the declaration and use of the command object in relation to the Album domain class. Thus, it seems that any command object is still closely related to the domain classes. I am sure that my confusion is completely connected with my lack of understanding, and therefore I want to find any clarifications. Thanks.

+6
source share
2 answers

They seem to wrap around domain classes ...

You can use command objects in this way, but this is not their main use.

Command objects are useful when you want to encapsulate a group of query parameters and do something together with them. This may or may not have anything to do with domain classes.

For example, you might have a Grails application that doesn't have any domain classes at all, and command objects can be really useful. Imagine a Grails application, which is just a service layer that receives a request from web forms or REST requests using the JSON body or something else, and the Grails application will receive these requests, check the input, maybe do some math or anything at all, and then make a REST call to another process that can store them in a database or generate reports or something else. In this situation, there are many reasons why you can use command objects, even if none of the domain classes are involved.

Do not get confused when thinking that team objects must be bound to domain classes. Sometimes they are, but do not limit your thinking of them in this context. Use command objects if you want to link a group of query parameters together and do something with them.

+7
source

I tend to use command objects that correspond to what happens in the user interface layer, the presentation form can be checked using command objects, and then transferred to the services that do the job of saving them. Many times, it makes sense that your domain model is different from the user interface stream that you are working with.

My domain layer can also have weaker restrictions than some of the team objects if I want certain streams to provide enough information.

+3
source

Source: https://habr.com/ru/post/977715/


All Articles