Grails Command Objects - What is the motivation behind them? - grails

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.

Related

grails design classes and external data (spreadsheet)

Having a bit of an issues on design, and was hoping I could ask for advice here. Accept that grails may be the completely wrong tool, but such is life.
So have been working away on a web app that basically just present a lot of information from a google spreadsheet and sends some updates back. I have managed to get most of it working but decided to rewrite it to get rid of my ridiculous spaggeti code as well as the many pieces of broken code that lays strewn throughout the project.
The system is relatively small, two-three users. The amount of data is small as well. One worksheets with max 500 rows (four columns) and another one with potentially 5000 (four columns). So all small, but I need it (well, want it) to stay in the google spreadsheet and the application feeding from there.
There are three classes I need for this to work,
Google authentication class keeps information on keys and tokens to speak to google
Google Spreadsheet class keeps information on the source spreadsheet
Google Data Entry keeps information from the two spreadsheets based on a unique id
So here is my question, what should I define these classes as. Thought I would use Domain classes, but then realised that these are stored in a database. Is there a way of keeping domain classes session dependent, I.E., that two users can use the same app on the same server but never see each others data and that the data is destroyed on logout. If not, is there some other class I can use that works similar to Domain class but kept in memory user/session specific.
I'm not really sure what exactly your requirements for those classes, but here are some thoughts anyway.
First, you may want to ask if they can't just be "normal" classes in src/groovy. I say "normal" here in the sense that they may just encapsulate some data and behavior, and you are responsible to create instances of them and call the methods appropriately when needed.
But, if you want to tie some data and behavior to the user session (as you seem to, because you asked for session dependent domain classes), you may want to use a Grails Service with session scope. When you do that, Grails will use a different instance of the service for each session of your application, and reuse the same instance for the same session until it ends.
You may also use a bit of each thing, using one service with session scope and have other classes representing the data that you pass around from the controllers to the service and vice-versa. These could actually be Command Objects if you needed validation and data binding, for example.

When should I consider implementing a Service in Grails?

I'm new to Grails and web development. I started doing a project on Schedule management website stuff. I came across the Service concept that is provided by Grails. I understood the concept, but still I have confusion on when to use services.
For example, I need to implement a search module, where the manager can search for a user to find his schedules. In this case it will be good to implement it as a controller or as a service?
So,
When and where should I use Service?
To add to Grooveek's answer;
It is also nice to use Services to keep your Controllers nice and clean.
So Views just render data to the screen, Domain objects store state, Controllers route the user around the application, and Services perform the work.
I don't have enough reputation to comment on an answer or vote up so I have to provide an answer that really should be a comment. Anyways...
+1 on #tim_yates answer. Gotta love thin controllers. 2 things that I would add to the description of a controller:
Would be to translate parameters from the browser before hitting a service (e.g. Date, number, etc.)
Would be to translate data returned from services into something consumable for the views.
For me, ideally, services would never deal with translating a String parameter to it's inherent type. Or deal with building a model to be displayed on a view.
What and where I should use Service?
When you want your controller do to something that may be reused by other controllers
In our application we're doing a functional separation of service. We have a CorePersistanceService, which provides method to create, delete, update and manipulate Core Domain Classes (core for us).
I think persistance services are a good way to reuse GORM code throughout Grails code. You can create method in domain classes, but I don't like that, it's way less maintanable I think
We have a PDFService class for our PDF creation, a SolrService which connect to Solr, a Statisticservice that gather all our methods which collects statictics on our datas
Services in Grails are a manner to gather methods around a particular functional theme, in order to give possibility to reuse them in controllers (I forgot to mention our SecurityService, which is a pretty good Cross-Applications Example)

Struts2 and multiple active wizards / workflows

I'm currently working on a Struts2 application that integrates a wizard / workflow in order to produce the desired results. To make it more clear, there is a business object that is changed on three different pages (mostly with AJAX calls). At the moment I'm using a ModelDriven action (that's extended by all the actions working with the same business object) coupled with the Scope interceptor. While this works okay if the user is handling data for only one business object at a time, if the user opens the wizard for different objects in multiple tabs (and we all do this when we want to finish things faster) everything will get messy, mostly due to the fact that I have only one business object stored in the session.
I have read a few articles about using a Conversation Scope Interceptor (main article) and about using the Scope plug-in (here). However, both approaches seem to have problems:
the Conversation Scope Interceptor doesn't auto-expire the conversations, nor does it integrate properly with Struts2;
the Scope plug-in lacks proper documentation and the last build was made in 2007 (and actually includes some of the ideas written by Mark Menard when he defines his Conversation Scope Interceptor, though it doesn't use the same code).
Spring's WebFlow plug-in seems a bit too complex to be used at the moment. I'm currently looking for something that can be implemented in a few hours time, though I don't mind if you can suggest something that works as needed, even if it requires more time than I'd currently want to spend on this now.
So, seasoned Struts2 developers, what do you suggest? How should I implement this?
Okay this isn't a fully baked idea. But seeing as no else has provided anything, here is what I would start with.
1) See if you can move the whole flow into a single page. I'm a big believer in the less pages is better approach. It doesn't reduce complexity for the application at all, but the user generally finds the interface a lot more intuitive. One of the easiest ways to go about this is by using the json plugin and a lot of ajax calls to your json services.
2) If you must transition between pages (or simply think it is too much client side work to implement #1) then I'd look to the s:token tag. The very first page to kick off a flow will use this tag, which will create a unique value each invocation. You will store a map in your session of model objects. An action will need to be provided with a model by looking it up from the session.
There are a couple challenges with #2. One how do you keep the session from getting too many domain objects? a) Well it might not matter, if the session is set to say six hours you can be rather sure that over night they will get cleared up. b) provided a self management interface which can get/set/list objects in the session. It might be what you thought of at first but it would let a worker do a certain amount and then stop and work on another. If the unit of work has some meaningful name (an invoice number or whatever) it could be quite useful.
A little more sophistication would be to move the model objects out of the session and into the service layer. At which point when inserted you would set an insertion time. You would probably need a manager to hold each type of model object and each manager would have a daemon thread that would periodically scan the map of domain objects and clean out expired ones.
You can figure out more complicated system by kicking a flow off with a token and then using another token on each page. "flowId" and "currentPageId" respectively, then you can graph allowable transitions.
Mind you at this point spring web flow is starting to look pretty good.
There is now a conversation plugin for Struts2 that achieves all these goals with very little work required by the developer: http://code.google.com/p/struts2-conversation/
It has:
-nested conversations
-cleanup of dead conversations
-convention over configuration with annotations and naming conventions
-inherited conversations
-fully integrated with Struts2
-the conversation scope can also be used by Spring IoC container-managed beans
Hope it helps somebody.

What’s the best approach to work with in memory domain objects in Grails?

I’m working on a Grail’s project that has some Domain objects not persisted on the database. They are managed thru a REST API, so all their CRUD operations will be done with this API instead of the database.
The point is to still be able to use some interesting Grails plug-ins (like searching using Compass).
For instance, the administration the Domain objects Users is going to be managed with the REST API, so when the Users list is displayed a the REST method to retrieve the list of users will be invoked on the remote server. I hope this use case is clear enough :)
I can think on several ways to design that but I'm not sure what’s the best:
Should I create the Domain Objects in the controller (and delete the
previous Users stored in memory)?
It seems it’s possible to define a Domain Class not persistable (with
mapping I think) but I’m not sure if this is the best approach or
where to load the data.
It is better not to model as a Grails the User as Domain object?
Thanks in advance!
I would wrap the REST interactions in a service, and call the service from a controller. In that case, the service would get the response and create its objects, passing the list back to the controller. Controllers should just handle incoming requests, invoke application components, and return responses.
It seems you want models to represent the data in the other application, which is a good idea. Since you don't need GORM, you might want to define them in the 'groovy' folder of your app instead of the domain models folder. Then I think they will just be objects.
I'd go with non-domain objects in src folder - though, need to check if it's possible to use the mentioned plugins with them.
I wonder what domain class functionality you wish to get out of non-persistent classes?

ASP.NET MVC models when using external web services

I'm getting started on a new MVC project where there are some peculiar rules and a little bit of strangeness, and it has me puzzled. Specifically, I have access to a database containing all of my data, but it has to be handled entirely through an external web service. Don't ask me why, I don't understand the reasons. That's just how it is.
So the CRUD will be handled via this API. I'm planning on creating a service layer that will wrap up all the calls, but I'm having trouble wrapping my head around the model... To create my model-based domain objects (customers, orders, so on..) should I:
Create them all manually
Create a dummy database and point an ORM at it
Point an ORM at the existing database but ignore the ORM's persistence in lieu of the API.
I feel like I've got all the information I need to build this out, but I'm getting caught up with the API. Any pointers or advice would be greatly appreciated.
Depending on the scale of what you're doing option 3 is dangerous as you're assuming the database model is the same as that exposed by the external service. Options 1 and 2 aren't IMHO much different from each other - in either case you'll have to decide what your objects, properties and behaviours are going to be - it just boils down to whether you're more comfortable doing it in classes or database tables.
The key thing is to make sure that the external service calls are hidden behind some sort of wrapper. Personally I'd then put a repository on top of that to handle querying the external service wrapper and return domain objects.
In general, ORMs are not known for their ability to generate clean domain model classes. ORMs are known for creating data layers, which you don't appear to need in this case.
You could probably use a code generation tool like T4 to code generate a first pass at your domain model classes, based on either the web service or the database, if that would save you time. Otherwise, you probably would just manually create the domain objects. Even if you code generate a first pass at your domain objects, it's unlikely there is a clean 1-1 mapping to your domain objects from either the database or web service, so you will likely need to spend significant time manually editing your code generated domain classes anyway.

Resources