Multiple Service in Spring Boot App, is it good practice? - spring-boot

I am writing my first bigger API, which is based on three entities (cinema, movies, movie properties). I try divide my methods like below:
MovieServiceImpl:
saveMovie(), findMovieByID(), deleteMovieByID,
showMovieWithCinemasList(), enrolledPropertyToMovie()
CinemaServiceImpl
saveCinema(), enrolledMovieToCinema(), showCinemasWithMovieList()
PropertyServiceImpl
saveProperty(), findPropertyByID()
ReservationServiceImpl
showFreePlaceOnMovie(), showDateChosenMovie(), showRepertoire(),
showCinemasWithMoviesLisT(), multiplePlaceReservation()
Question
Whether it is compatible with the Single Responsibility Principle (SRP).
And it is a good practice to divide it into smaller Services if not what should I do?

Your question is a bit unclear.
Single Responsibility Principle mandates single responsibility for a single structural unit of work (class, module, interface, method, whateverunityourlanguage has), i.e. one entity/unit responsible(/solving) one particular problem.
For instance, if you have a method:
Person getPersonById(int id) {...}
you should never implement validation or authentication logic in it; instead, you should delegate that responsibility to another layer/object.
This has almost nothing to do with "can I have several types in the application?", and to be honest, I can't think of any application (unless it's a really small console app), which doesn't have several structural units (entities, like class, interface, etc.) in itself.
Your example doesn't show anything about SRP, but rather solely demonstrates, that you have different types for different business domain models, and that's much, much better way of designing application/types, in contrast to having one messy class for working with different domain objects/logic.
If, however, you violate SRP in the methods of those classes, that's another story, and we can't address it here, as you don't show implementations.
I still think, that your question was more about having different types, instead of incorporating all of them in one (a horrible idea!), and in your example, Movie, Cinema and Property are three different domain entities, which is - again - good.
Regarding:
And it is a good practice to divide it into smaller Services if not what should I do?
It's unclear what do you mean in "smaller services" and what is your question about. It seems to me, that you're working with nTier/Layered architecture, and only thing I can tell you, that - yes, it's good to separate responsibility layers.

Blockquote
I still think, that your question was more about having different types, instead of incorporating all of them in one (a horrible idea!), and in your example, Movie, Cinema and Property are three different domain entities, which is - again - good.
Yes my question was just about it!
And by the way, you made me realize that it should separate the validations to other methods so that my code becomes better and meets the SRP as well.
Thanks for the answer, although it seemed logical to me, I needed confirmation from someone experienced. Thank you very much!!!

Related

Multiple Controllers appropriate with one entity in spring framework

I'm starting to develop website that use the spring framework.I have three controller.There are newCustomerController,editCustomerController and deleteCustomerController.These controllers are mapped with view that use for create update and delete, but I create only customer.
So, I would like to know.Is it appropriate to declare the controllers like this.
Thank
The answer to this question is subjective and maybe more a topic for https://softwareengineering.stackexchange.com/. However, there is something very spring related about it that I would like to comment.
There are a few principles that attempt at guiding developers of how to strike a good balance when thinking about designing the classes. One of those is the Single responsibility principle.
In object-oriented programming, the single responsibility principle
states that every class should have a single responsibility, and that
responsibility should be entirely encapsulated by the class. All its
services should be narrowly aligned with that responsibility
A catchier explanation is
A class or module should have one, and only one, reason to change.
However, its still often hard to reason about it properly.
Nevertheless, Spring gives you means for it (think of this statement as a poetic freedom of interpretation). Embrace constructor based dependency injection. There are quite a few reasons why you should consider constructor based dependency injection, but the part relevent to your question is adressed in the quote from the blog
An often faced argument I get is: “Constructors just get too verbose
if I have 6 or 7 dependencies. With fields only, this is fine”.
Awesome, you’ve effectively worked around a clear indicator that the
code you write is doing way too much. An increase in the number of
dependencies a type has should hurt, as it makes you think about
whether you should split up the component into multiple ones.
In other words, if you stick to constructor based injection, and your constructor turns a bit ugly, the class is most likely doing too much and you should consider redesigning.
The same works the other way around, if your operations are a part of the logical whole (like CRUD operations), and they use the same dependencies (now "measurable" by the count and the type of the injected deps) with no clear ideas of what can cause the operations to evolve independently of each other, than no reason to split to separate classes/components.
It should be better if you define one controller for Customer class and in that class you should have all methods related to customer operations (edit,delete,create and read).

Using an object oriented approach in Ruby

I have two classes, Class A and Class B.
I've recently noticed that they share a lot of the same code. For example:
def viewable_by?(user)
super || clinic.has_staff_member?(user) || user.system_admin? || self.person == user.person
end
I want to minimize the code duplicated between the classes. But in refactoring, I've found that much of it doesn't fit neatly into one class that falls cleanly in the Single Responsibility Principle. I want to put it all into a single module, but the methods will have to do with time formatting, viewing permissions, and a few other things.
As I see it, I have a few choices. (And I bet you can suggest others.) From an object oriented point of view, which approach should I go with and why?
Use one single module shared between both of the classes. It may
not have a specific single responsibility, but it does clean up the
code significantly, and keeps it all in one place.
Make tiny classes and mix in to both classes as modules. They
will all have a single responsibility, but there will be many of
them, some of which may only have one method. Seems like a waste.
Perhaps use a presenter for things like time formatting, and a
permissions module shared between both classes. Perhaps "cleaner,"
but methods are going to be everywhere.
Another possibility I haven't yet considered?
EDIT
This question had previously mentioned Clinic::Appointment and Clinic::Visit classes, rather than A and B. Answers may refer to appointments and visits.
This is a neat question because it deals in a great way with the overall strucuture of your project. I understand that Appointment and Visit are separated things, and an Visit don't need to be linked to an Appointment.
For authorization methods, like viewable_by?, I recommend move all authorizations to other place - you might want to check the cancan structure, that have worked well for many Rails projects, and most likely will work well for any application, even coding an authorization system yourself. So in part, my answer for you is to use (3).
However, since not all code that is shared by the two classes are for authorization purposes, I would try to classify a set of methods, and give an answer for each class of methods you could think of. For method classes that have a similar behavior I would try to encapsulate in a module and include it (so just like (1), but in smaller parts). For example one module HasVisitors with methods like got_on_time? and was_conclusive? (well, maybe not the best examples, but you get it). When your model has a broader scope, like Authorization, that is present in most of your classes, then it is time to go to (3).
I suggest you stop and think again if you should have a Visit class apart from Appointment and it relationship, but not now. After got at home, have fun, take it off from your head, then think again next day.
Would the design be clearer if you shifted the responsibilities? e.g. user.can_view?(resource)

How to explain to someone that a data structure should not draw itself, explaining separation of concerns?

I have another programmer who I'm trying to explain why it is that a UI component should not also be a data-structure.
For instance say that you get a data-structure that contains a record-set from the "database", and you wish to display that record-set in a UI component within your application.
According to this programmer (who will remain nameless, he's young and I'm teaching him...), we should subclass the data-structure into a class that will draw the UI component within our application!!!!!!
And thus according to this logic, the record-set should manage the drawing of the UI.
******Head Desk*****
I know that asking a record-set to draw itself is wrong, because, if you wish to render the same data-structure on more than one type of component on your UI, you are going to have a real mess on your hands; you'll need to extend yet another class for each and every UI component that you render from the base-class of your record-set;
I am well aware of the "cleanliness" of the of the MVC pattern (and by that what I really mean is you don't confuse your data (the Model) with your UI (the view) or the actions that take place on the data (the Controller more or less...okay not really the API should really handle that...and the Controller should just make as few calls to it as it can, telling it which view to render)) But it's certainly alot cleaner than using data-structures to render UI components!
Is there any other advice I could send his way other than the example above? I understand that when you first learn OOP you go through "a stage" where you where just want to extend everything.
Followed by a stage when you think that Design Patterns are the solution every single problem...which isn't entirely correct either...thanks Jeff.
Is there a way that I can gently nudge this kid in the right direction? Do you have any more examples that might help explain my point to him?
Have you heard of Martin Fowler?
Separating User Interface
Code
Anyway, if he wants to go further in that direction of adding render methods to his data controls, have him look at "loose coupling". It's okay to create some generic type of interface that gets him halfway there, but the UI component should take it the rest of the way.
This boils down to functional vs. non-functional responsibilities. What the data structure does and how it's visualized are two completely separate things -- essentially the root of the MVC pattern.
There's also a notion of circular dependencies here. Since the UI must know about the data structures, if you allow the data structures to then depend on the UI, you've got yourself a nice little ball of mud.
Generally on the point of decoupling:
Not only can there be different components of the UI rendering the same data structure. You may even have completely different UIs (Web, Desktop Application, ...) Now of course, you could subclass Person with WebPerson and DesktopPerson (this already sounds wrong, doesn't it? The naming is simply not about the kind of Person - it's about something else).
Each UI could work on different kinds of Persons, e.g. Teacher and Student. So we get WebPerson, WebTeacher, WebStudent, DesktopPerson, DesktopTeacher and DesktopStudent.
Now let's say, WebPerson defines the method "drawAddressFields()" to draw a web version of the address fields. But since WebTeacher has to derive from Teacher to use the additional data field "salary" (and let's assume single inheritance), it must implement "drawAddressFields()" once again!
So maybe the argument of "this will cause much more work" will help to create some motivation :-)
BTW, it will automatically lead to creating some delegate that implements the code of drawAddressField(), which will then evolve to creating a component that does the drawing separately from the data structure.

Using MVC, how should one handle communication between Views? Between Models?

Question number three in my quest to properly understand MVC before I implement it:
I have two cases in mind:
The primary application
window needs to launch the
preferences window. (One View
invoking another View.)
The primary Model for an application
needs to access a property
in the preferences Model. (One Model
accessing another Model.)
These questions are related in that they both involve communication across Model-View-Controller triplets, a topic that I haven't found much discussion of in my Googling.
The obvious way to fix this is to wrap everything in a top-level "application" object that handles transactions between Models and allows Controllers to invoke one another's methods. I have seen this implemented, but I'm not convinced its a good idea. I can also see possibilities involving Controllers observing more than one Model and responding to more than one View, but this seems like its going to become very cluttered and difficult to follow.
Suggestions on how best to implement this sort of cross-talk? I feel like its a very obvious question, but I've been unable to find a well-documented solution.
On a broader note, if anyone has a link that shows typical approaches to these sorts of MVC issues, I would love to see it. I haven't had much luck finding solid, non-trivial references. Examples in Python would be lovely, but I'll gladly read anything.
Edit 1:
I see some pretty interesting things being said below and in general no-one seems to have a problem with the approach I've described. It is already almost a lazy form of the FrontController design that Vincent is describing. I certainly don't foresee any problems in implementing that pattern, however, it doesn't seem that anyone has really addressed the question in regards to communication amongst Models. All the answers seem to be addressing communication among objects in a single Model. I'm more interested in maintaining separate Models for separate components of the application, so that I'm not stuffing fifty state properties into a single Model class. Should I be maintaining them as sub-Models instead?
With respect to (1), views don't invoke other views. They invoke controller actions that may result in other views being rendered. In your case, the primary application window contains a user interface element (button, link) that invokes a controller action to display the preferences window.
With respect to (3), model components certainly could be related to one another. This isn't unexpected nor to be avoided, necessarily. For instance your Customer model may have an associated set of Orders. It would be perfectly natural to access the customer's orders via a method in the Customer class.
You might want to take a look at the MVC page on wikipedia for an overview.
You may want to consider looking up the Front Controller design pattern.
The Front Controller pattern defines a single component that is responsible for processing application requests. A front controller centralizes functions such as view selection, security, and templating, and applies them consistently across all pages or views. Consequently, when the behavior of these functions need to change, only a small part of the application needs to be changed: the controller and its helper classes.
This way all requests from the view goes to the FrontController who then decides which specific action (controller) to invoke. Sometimes, it could forward straight to another view as in your first case.
There is no problem with multiple objects in the model talking to each other. In fact that will be very common. The way I see it, all the objects in the Model act like one component to represent the data and operations on the data.
This article might help. And this one.
Model does not mean a single model object. The model is the subset of the entirety of your domain model which is directly related to the controller actions and the views in question.

Fat models, skinny controllers and the MVC design pattern

I just read a blog post that explains MVC with a banking analogy. I have a few months of experience with web application development with an MVC framework (CakePHP), so I get the basics, but I began to see a theme that made me think I'm taking a flawed approach to where I put my logic:
Fat models, skinny controllers
Keep as much business logic in the models as possible
In my app, models are anorexic and controllers are obese. I have all business logic in the controllers and nothing besides associations and validation rules in the models.
Scanning through my controllers, I can now identify a lot of logic that should probably go in a model:
The app has lists, which contain items, and the items can be ranked. The sorting logic which puts the list in ranked order is in a controller.
Similarly, items (Item model) also have images (Image model). Each item may have a default image (designated by image_id in the items table). When an item is displayed with its images, the default image should appear first. I have the logic that does this in a controller.
When a list is displayed, related lists are displayed in the sidebar. The logic to determine which lists are related is in a controller.
Now to my questions:
With the examples I gave above, am I on the right track in thinking that those are instances of logic presently in a controller that belongs in a model?
What are some other areas of logic, common to web apps, that should go into models?
I'm sure identifying this problem and changing my design pattern is half the battle, but even if I decide to take those examples I gave above and try to move that logic to a model, I wouldn't know where to begin. Can anyone point me in the right direction by posting some code here, or linking to some good learning resources? CakePHP specific help would be great, but I'm sure anything MVC will suffice.
It's a bit tough to give you the "right" answers, since some of them deal with the specifics of the framework (regardless of the ones you are working with).
At least in terms of CakePHP:
Yes
Anything that deals with data or data manipulation should be in a model. In terms of CakePHP what about a simple find() method? ... If there is a chance that it will do something "special" (i.e. recall a specific set of 'condition'), which you might need elsewhere, that's a good excuse to wrap inside a model's method.
Unfortunately there is never an easy answer, and refactoring of the code is a natural process. Sometimes you just wake up an go: "holy macaroni... that should be in the model!" (well maybe you don't do that, but I have :))
I'm using at least these two 'tests' to check if my logic is in the right place:
1) If I write a unittest, is is easy to only create the one 'real' object to do the test on (= the object that you are using in production) and not include lots of others, except for maybe some value objects. Needing both an actual model object and an actual controller object to do a test could be a signal you need to move functionality.
2) Ask myself the question: what if I added another way to use these classes, would I need to duplicate functionality in a way that is nearly copy-paste? ... That's also probably a good reason to move that functionality.
also interesting: http://www.martinfowler.com/bliki/AnemicDomainModel.html

Resources