When should I consider implementing a Service in Grails? - 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)

Related

Where should I add a List All Users function when using MVC?

I'm aware that in model-view-controller, the Model is the class part.
If I have a User class and instantiate an object, the object must refer to a single user from the database.
So I'll have the CRUD methods on the user, for that specific user.
But if I need a function to run a SELECT * FROM Users, should I create a function within the User class? Or a function in a helper file? Or in the controller? Where should it go, in order to respect the MVC pattern?
I mean, it makes no sense to instantiate a User object just to run a function to display the Users table.
I'm not sure if this will raise "primarily opinion based" flags. I just don't know where those functions should go. If you guys consider the question worth closing, it's ok. But tell me in the comments in which stack community I should ask this.
Back up a bit. Let's go foundational for a moment.
In the MVC pattern
The model is your state (in simple terms), meaning a representation of the data important to the business functionality you are working with
The view is a way of presenting the state to the user (NOTE user here could be another system, as you can use MVC patterns for service endpoints)
The controller ensures the model gets to the view and back out of the view
In a system designed with good separation of state, business functions are not present in the model, the view or the controller. You segregate business functionality into its own class library. Why? You never know when the application will require a mobile (native, not web) implementation or a desktop implementation or maybe even become part of a windows service.
As for getting at data, proper separation of concerns states the data access is separate not only from the model, view and controller, but also from the business functionality. This is why DALs are created.
Before going on, let's go to your questions.
should I create a function within the User class? This is an "active record" pattern, which is largely deprecated today, as it closely couples behavior and state. I am sure there are still some instances where it applies, but I would not use it.
Or a function in a helper file? Better option, as you can separate it out. But I am not fond of "everything in a single project" approach, personally.
Or in the controller? Never, despite Scott Gu's first MVC examples where he put LINQ to SQL (another groan?) in the controller.
Where should it go, in order to respect the MVC pattern?
Here is my suggestion:
Create a DAL project to access the data. One possible pattern that works nicely here is the repository pattern. If you utilize the same data type for your keys in all/most tables, you can create a generic repository and then derive individual versions for specific data. Okay, so this one is really old, but looking over it, it still has the high level concepts (https://gregorybeamer.wordpress.com/2010/08/10/generics-on-the-data-access-layer)
Create a core project for the business logic, if needed. I do this every time, as it allows me to test the ideas on the DAL through unit tests. Yes, I can test directly in the MVC project (and do), but I like a clean separation as you rarely find 0% business rules in a solution.
Have the core pull the data from the DAL project and the MVC project use the core project. Nice flow. Easy to unit test. etc.
If you want this in a single project, then separate out the bits into different folders so you can make individual projects, if needed, in the future.
For the love of all things good and holy, don't use the repository pattern. #GregoryABeamer has a great answer in all respects, except recommending you create repository instances to access your entities. Your ORM (most likely Entity Framework) covers this, and completely replaces the concepts of repositories and unit of work.
Simply, if you need something from your database, hit your ORM directly in your controller. If you prefer, you can still add a level of abstraction to hide the use of the ORM itself, such that you could more easily switch out the data access with another ORM, Web Api, etc. Just don't do a traditional unit of work with tens or hundreds of repository instances. If you're interested, you can read a series of posts I wrote about that on my blog. I use the term "repository" with my approach, but mostly just to contrast with the typical "generic" repository approach you find scattered all over the interwebs.
I'd use some kind of 'Repository' layer. Then, my controller calls the UserRepository GetAll method and sends the data to View layer.

Model View Controller Store - Should I create more than one store object in this situation?

I'm still not used to the MVCS design pattern. I read in a book that if I was planning to create an app that gets information from an external source, it's better to use MVCS instead of MVC.
I'm currently working on an ios app that gets information from multiple external sources. For example, I'll be fetching info about the weather from a web service, driving directions/time probably from Google, and data from our database via a web service as well.
My question is, do I need to create more than one store object in this situation? Like create a store object for each of the external sources? Or do I just create one for all of them?
I think it really depends on your design approach as you can have dozens of different design approaches which all respect the MVC principles and that therefore are all correct.
Personally I would suggest to try to decompose the problem as much as you can in smaller problems, in order to get the most from the flexibility that a objected oriented environment gives you.
In this case, for instance, you could think about having an abstract store class in which you implement the common functionalities you need to have and then subclassing it for each different web service you need to use and implementing the other functionalities related to that specific service. It's just an idea! I hope this helps.

Shouldn't Grails GORM calls be in the service and not controller layer?

I'm trying to decide, according to Grails best practices and MVC patterns, when is the correct time to introduce a Service and not keep fattening controllers. I find it somewhat conflicting, what I've read about best practices and what appears to be common practice, so would love to hear what others think about this.
With GORM calls in mind, I would have expected that anything to do with GORM should really go into a service. Although I don't practice this myself, especially when writing very basic controller methods like show that simply perform a get() on a domain class and then render a view to show the details of the retrieved object.
However, after following books like 'Clean Code' and similar books, well maintained code should be cohesive and methods should ideally perform a single task only. So in the perfect world, would the show method in a controller be responsible only for determining the object to display before rendering a view? The retrieval from the database could go into a method in the database that's sole task is to retrieve from the DB and throw an exception if not found etc.
But yes, this does somewhat seem like overkill.
So taking the step a bit further, the create() or update() methods. Again currently Grails' generated code puts everything into the controller, no use of a service at all.
So when would the recommended point be that we need to use a Service? Is it only when something transactional has to take place, for instance, on a create() call, we might also want to write a record to a Log file to keep an audit log of sorts. Surely this warrants a service?
I'd love to hear what others feel is the correct time to introduce services, I imagine it differs greatly person to person.
I recommend you this post: http://www.infoq.com/articles/grails-best-practices
We are creating static methods in Domain class to encapsulate queries. Service are used only for transactional operations or very complex queries with multiple domains interaction. Controllers simply call domains or services methods.

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?

Architecting ASP.net MVC App to use repositories and services

I recently started reading about ASP.net MVC and after getting excited about the concept, i started to migrate all my webform project to MVC but i am having a hard time keeping my controller skinny even after following all the good advices out there (or maybe i just don't get it ... ).
The website i deal with has Articles, Videos, Quotes ... and each of these entities have categories, comments, images that can be associated with it. I am using Linq to sql for database operations and for each of these Entities, i have a Repository, and for each repository, i create a service to be used in the controller.
so i have -
ArticleRepository
ArticleCategoryRepository
ArticleCommentRepository
and the corresponding service
ArticleService
ArticleCategoryService ...
you see the picture.
The problem i have is that i have one controller for article,category and comment because i thought that having ArticleController handle all of that might make sense, but now i have to pass all of the services needed to the Controller constructor. So i would like to know what it is that i am doing wrong. Are my services not designed properly? should i create Bigger service to encapsulate smaller services and use them in my controller? or should i have an articleCategory Controller and an articleComment Controller?
A page viewed by the user is made of all of that, thee article to be viewed,the comments associated with it, a listing of the categories to witch it applies ... how can i efficiently break down the controller to keep it "skinny" and solve my headache?
Thank you!
I hope my question is not too long to be read ...
This is the side effect of following the Single Responsibility Pattern. If each class is designed for only one purpose, then you're going to end up with a lot of classes. This is a good thing. Don't be afraid of it. It will make your life a lot easier in the long run when it comes to swapping out components as well as debugging which components of your system aren't working.
Personally, I prefer putting more of my domain logic in the actual domain entities (e.g. article.AddComment(comment) instead of articleCommentService.AddComment(article, comment)), but your approach is perfectly fine as well.
I think you are headed in the right direction. The question is how to instantiate your services? I'm no MVC.NET guru, but have done plenty of service oriented Java projects and exactly the pattern you are discussing.
In Java land we would usually use Spring to inject singleton beans.
1) You can do the same thing in .NET, using dependency injection frameworks.
2) You can instantiate services as needed in the method, if they are lightweight enough.
3) You can create static service members in each controller as long as you write them to be threadsafe, to reduce object churn. This is the approach I use in many cases.
4) You can even create a simple, global service factory that all controllers access, which could simply be a class of singletons.
Do some Googling on .NET dependency injection as well.

Resources