Java EE best design approach. business logic layer? - spring

The project I am working with uses JSF + Spring + Hibernate.
This is a design question that I have often been confused about.
I currently inherited a project that contains a dao -> service -> view -> controller "layered" approach.
The "Controller" layer / tier? currently has all logic and objects that interact with the front end. I have been told that it is good practice to separate this into two layers/tiers, where the "Controller" layer/tier only contains methods/objects that interact with the front end and a second layer (bm?) that contains all business logic used by the controller.
1st.) What would the purpose be of dividing up the controller in such a way?
2nd.) Is there anything wrong with leaving it the way it currently is?

1st.) What would the purpose be of dividing up the controller in such a way?
You must handle the business logic in Service Layer. Benefits of separating the business entities from Controller/UI Layer :
You can reuse the business entities with another client sections. Example : if you are developing a web based application as UI, later you also developed a Desktop UI. In this case you can reuse your Business Layer operations with multiple UIs. You can also use business layer to work as a web service.
Decoupled business operations are easier to manage. If someone from development team has no idea how UI code works and only wants to correct some business logic, he can does.
2nd.) Is there anything wrong with leaving it the way it currently is?
If you are new to Layered Architecture it will take some time to understand and implement the desired layers. It depends on time frame and application requirements. If you are planning to use the above points in your application go with layered architecture otherwise go with current implementation.

If you're asking why it's a good idea to have a service layer that's used by the view, then the answer is that more often than not you want to access services from parts of the application that are different from a specific view.
For instance, suppose you had logic to validate an order, which at first was primarily used on some /order.xhtml page. It wouldn't hurt that page to have the Service and corresponding objects (say Order) right there in the view.
But then the requirement comes to do order validation from a batch job. If the code for that validation is tightly coupled to your view, this will be impossible or very hard and most likely be very awkward (I've seen people mocking a JSP PageContext since some business logic happened to require it).
There are quite some other situations where this creeps up, like e.g. an external API via JAX-RS, a totally different view (page for another user, or perhaps a mobile targeted UI), etc.

Business logic layer should not be implemented on the service layer.
DAO/Service Layer -> Business Logic Layer -> UI Controllers
-rico

Related

Layered architecture mvc

I'm creating a web app using an MVC framework. I thought of adding a layer between the controller and the domain models, I think it's called application layer in DDD, to avoid putting logic that is specific to a certain use case in the domain models.
The controller will only interact with this layer and this layer will orchestrate the operation using the domain models. This layer will be kept as thin as possible pushing all the logic that is not use case specific to the domain model.
I will call the classes that belong to this layer DomainCtrl.
Example login scenario:
Model: LoginForm
DomainCtrl: AuthCtrl
UI: ui controller
1.ui controller receives request
2.creates instance of AuthCtrl
3.AuthCtrl creates instance of a LoginForm and fill it with request data passed to authCtrl
4.LoginForm performs the login
5.authCtrl does other things that are specific to this specific way of login -> returns errors to ui controller
Is this a good way to organize an app?
Your question
Is this a good way to structure an app
is a very loaded question. The simple answer is Yes, but the more correct answer is It depends.
Let's start with the simple answer. Having your main application be unaware of the UI is generally a good idea. It means that you can easily consume your application from various places. In DDD this outer layer is usually called Application Layer. It is mainly responsible for orchestrating interactions between your domain, persistence and other resources that you might rely on. This also allows you to have your domain at the center unaware of everything else. This makes your domain easily testable and maintainable if implemented well.
Now the "it depends" part of the answer. DDD is not the only successful way to build an application, and in some cases it might be more of a hinderance than anything else. You have to ask yourself what is my app doing. Are there many domain specific rules? Am I only fetching and storing basic data etc? These are all questions you need to answer before you choose an architecture and technologies.
I would still say you probably won't go wrong by choosing the DDD approach as it is generally a good way to do things.
*Note: Your example is not that clear to me but you should be careful of spilling UI concepts into your domain/application. A login form is completely a UI concept as is auth to a certain extent. You can probably have your application return the details of your user, but the UI layer should decide if the user is allowed to proceed or not.
At a high level view, Yes
But it ultimately depends on "how" you logically separate your layers. In your scenario, I don't see any application layer.
I assume AuthCtrl is the domain? Who creates AuthCtrl? what layer does it exists?

Need help understanding MVC

To my understanding, MVC is a way to implement the separation of presentation tier from business and data tier. Am I understanding this correctly? If so, MVC should separate the business logic completely from presentation, right?
So to me it seems like javascript (or jquery) is somehow violating the MVC design since it takes over some of the logic on the client side, isn't it? Is model = data tier, controller = business tier, view = presentation tier? I think I have misunderstood the whole concept.
You seem to have a decent understanding of MVC. The trouble is that you are looking at two different potential MVC structures as one and the same. On the server, you can have data models, controllers, and views. On the client side, you can ALSO have data models, controllers, and views. If you want to look at your client side JavaScript as MVC, then jQuery is simply a utility that the view controllers can use to manipulate the view (the DOM).
Simply put, the client side doesn't always have to be only the view. If you use a web application client-side framework like Backbone, for example, then you can have models, views, and controllers all on the client side, which communicate with another, SEPARATE MVC structure on your server.
What you describe does actually pose a challenge for a lot of implementations. Frameworks such as the ASP.NET MVC Framework have been making attempts to auto-render JavaScript to the UI based on business logic in the middle tier (validation rules for form fields, primarily). But they're a long way off from having a truly compelling JavaScript user experience which doesn't repeat logic.
Personally, I like to think of the JavaScript as purely a UI concern. The application internally handles all of the logic. The JavaScript, as part of the UI, may duplicate some of that logic... but only for strictly UI purposes. Remember that the application should regress gracefully into a still-working state if the user has JavaScript disabled. That is, it should still use server-side (middle-tier) code to get the job done. All the JavaScript did was add a richer user experience to the UI layer.
JavaScript isn't the only culprit for this, either. Suppose you have a lot of validation logic in your middle tier defining what's valid or invalid for your objects. When you persist those objects to a database (which is on the periphery of the application just like the UI is), doesn't that database also contain duplicate validation logic? Non-nullable fields and such.
Congratulations! Your understanding of MVC is completely wrong. It has nothing to do with n-tier architecture (which is what you seem to be confusing it with).
The core idea of MVC is separation of concerns. This is used by dividing the application it two major layers:
model layer: contains all of the domain business logic and rules.
presentation layer: deals it user interface
The presentation then is further split into controllers (for handling the user input) and views (for dealing with response).
When applied to web applications, you either have MVC (or MVC-like) structure only on server-side, or, for larger and more complicated applications, you have separate MVC triads for both frontend and backend.
Also, when working with applications, the user of MVC is not human being, but the browser.
In latter case the backend acts like one data source for frontend application. An the whole frontend part of MVC is written in javascript.
P.S. In case if you are able to read PHP code, you can find a quite simple explanation of model layer in this answer. And, yes. It is the "simple version" because MVC is a pattern for enforcing a structure in large application, not for making a guesbook.
You can go to http://www.asp.net/mvc site and refer tutorials / samples to learn about MVC using Microsoft technologies.

Use client-side MVC/MVVM patterns with MVC server-side pattern

Considering the most popular MVC/MVVM client-side patterns (like Knockout.js, Angular.js, Ember.js, and others), I have one great doubt:
Also considering the modeling redundance in both sides, what is the advantages and disvantages to use those client-side patterns with MVC server-side patterns?
I struggled with how to answer this question... hopefully this helps, even if it is in a round-about way.
While some of the pros/cons have already been stated, I think the best rundown is in this answer.
For me, the biggest advantage to using client-side logic is the rich UI aspect.
But the key part of your question seems to be "model redundancy" (I'd call it duplicated logic, or at least having potential for duplicated logic). In my opinion, that is a problem which may exist independently of the pros/cons in the previous link.
So first of all, I think that the decision of whether or not to use a client-side framework should be made based on the well-documented pros and cons. Once that decision is made, the associated problems can be solved.
Lets assume you are using some sort of server-side framework/platform, as well as a client-side framework to provide a little bit of UI interactivity. Now there is a problem with where to put the model logic: on the client, server, or both.
One way to solve the problem is to define your model logic in only the client or the server. Then you have no code duplication, but it affects some of the higher-level pros/cons.
For example, if your model logic is 100% server-side, you lose some of the interactive part of the UI. Or, you are constantly throwing the model to/from the server, which will have a few cons.
If your model logic is 100% client-side, you could suffer performance problems, depending on the size of your view / model. This is one of the reasons Twitter is moving to a server-side processing model.
Then there is "both"... having model logic exist in both the client and the server. I think this is the best solution, as long as no logic is duplicated.
For example, on a shopping cart page, you may recalculate the cost of an order based on the price of a product, and a user-editable quantity box. I think this logic should only exist on the client. Other model properties that do not change once loaded are probably fine hosted on the server.
There's a lot of gray area here... I struggle with putting all the eggs in one basket. For example, choosing a client-side framework, creating a lot of client-side logic, and then [hypothetically] running into problems with performance, browser support, or something like that. Now you may want to tweak a page or two for performance (like move it server-side, a la Twitter). But I think being smart about how you structure your code will help mitigate that issue. If your code is maintainable and clean, moving logic from client to server won't be difficult.
The advantage is that the client side patterns are applicable at the client where the server has no direct reach. If you're building a rich, interactive HTML UI then use client side MVVM. Server side MVC may still be relevant in that case for delivering appropriate content to the client. For example, the ASP.NET WebAPI is a framework for creating HTTP APIs which has a similar controller architecture to the ASP.NET MVC framework. The API implemented with this framework may be called by client side code resulting in MVC on the server side and MVVM on the client side. Normally, when using MVC server side and MVVM client side, the responsibilities of the respective sides are very different and thus there is no redundancy.
The fact you an incorporate a MVVM model into an already implemented MVC framework is also a great thing, we recently added knockout to some new project pages to fit with in an already outdated MVC framework (old pages, not the framework itself).
I think MVVM is fantastic as the above answer states it provides an exceptional user experience with extremely fast response times, you can hide your validation calls in the backround with out slowing them down and its intuitive.
The pain however is that it is VERY hard to unit test and you can get some extremely LARGE javascript files, also the extra coding we've had to do as our legacy systems still run on IE6 is ridiculous.
But MVVM and MVC don't have to be used exclusively on there own, we use both. But having 3 levels of validation is something that still bugs me.
advantages
This can rock.
disvantages
You can screw it.
Seriously. Making use of transporting part of the frontend logic into the browser can boost your application development why you keep more strict data-processing encapsulated on server-side.
This is basically layering. Two layers, the one above talks with the one below and vice-versa:
[client] <--> [server]
You normally exchange value objects in a lightweight serialization format like Json between the two.
This can fairly well map what users expect in a useful structure while domain objects on server-side could not be that detailed.
However, the real power will be if the server-side is not in written in javascript at some certain point because I think you can not create well domain objects there. Consider Scala (or something similar expressive) then if you run into that issue.
Ten months later after this question, I have used the both patterns inside the same application.
The only problem was the need to map the models twice.
MVC (ASP.NET MVC 4 Web API)
The most important resource was the routes.
Models were created to database interactions and as arguments for
controllers' actions.
Controllers were created to manipulate the API
requisitions and to render the views.
Views were not modeled with
server-side models, but all the resources of Partial Views and
Sections.
MVVM (Knockout.js)
Models were created with the same properties as the server-side models.
Views were binded with models' properties, and decreased a lot of the views' size.
View-models were created with the values provided from API methods.
Overall, the MVC combination with MVVM were very useful, but it needed a big expertise and knowledge. Patience is required too, because you need to think about the responsibilites of each application layer.

Tips/tricks for architecting MVC in non-trivial desktop app

What are some lesser known tips for implementing a loosely-coupled MVC structure in a non-trivial desktop application (e.g. having at least two levels of views/controllers and more than one model)?
Use interfaces.
A lot. I like using the "IDoThisForYou" style (even in a language where this isn't idiomatic) because an interface represents a role that another class can use.
Make the controllers responsible for controlling interaction
The controllers control interaction between domain objects, services, etc.
Use events to pass information between controllers
Let every controller who needs information subscribe to the event. Use an interface.
Don't put presentation information on your domain objects
Instead, allow the controller to create a presenter or view model which has the information you need. This includes no "ToString()". If you're in a language without multiple inheritance you might end up with a bit of duplication between presenters. That's OK - duplication is better than coupling, and the UI changes a lot anyway.
Don't put logic in your gui
Instead, allow the controller to create a presenter or view mdoel which has the information you need. This includes train wrecks like "MyAnimal.Species.Name" - make it present "SpeciesName" instead.
Test it
Manually. There is no substitute. Unit and acceptance testing goes a long way, but there's nothing like bringing the app up and actually using the mess you wrote for finding out how messy it is. Don't pass it to the QAs without having a go yourself.
Oh, and don't mock out domain objects in unit tests. It's not worth it. Use a builder.
Declare event handlers in your interfaces (important for the views). This way you can loosely couple event handling which is managed by the controller. You may need to use the InvokeRequired when working with the view if your application is multi-threaded.

Which pattern would you choose for web application and why?

When you start a new web application, which pattern are you choosing between MVC and MVP and why?
(This answer is specific to web applications. For regular GUIs, see What are MVP and MVC and what is the difference?.)
Traditional MVC for GUI applications
This isn't really relevant to web applications, but here's how MVC traditionally worked in GUI applications:
The model contained the business objects.
The controller responded to UI interactions, and forwarded them to the model.
The view "subscribed" to the model, and updated itself whenever the model changed.
With this approach, you can have (1) multiple ways to update a given piece of data, and (2) multiple ways to view the same data. But you don't have to let every controller know about every view, or vice versa—everybody can just talk to the model.
MVC on the server
Rails, Django and other server-side frameworks all tend to use a particular version of MVC.
The model provides approximately 1 class per database table, and contains most of the business logic.
The view contains the actual HTML for the site, and as little code as possible. Basically, it's just templates.
The controller responds to HTTP requests, processes parameters, looks up model objects, and passes values to the view.
This seems to work very well for server-based web applications, and I've been very happy with it.
MVP on the client
However, if most of your code is written in JavaScript and runs in the web browser, you'll find lots of people using MVP these days. In this case, the roles are a bit different:
The model still contains all the basic entities of your business domain.
The view is a layer of fairly dumb widgets with little logic.
The presenter installs event handlers on the view widgets, it responds to events and it updates the model. In the other direction, the presenter listens for changes to the model, and when those changes occur, it updates the view widgets. So the presenter is a bidirectional pipeline between the model and the view, which never interact directly.
This model is popular because you can easily remove the view layer and write unit tests against the presenter and model. It's also much better suited to interactive applications where everything is updated constantly, as opposed to server applications where you deal with discrete requests and responses.
Here's some background reading:
Martin Fowler's encyclopedic summary of MVC, MVP and related approaches. There's a lot of good history here.
Martin Fowler's description of "Passive View", a variation of MVP.
Google's MVP + event bus
This is a new approach, described in this video from the Google AdWords team. It's designed to work well with caching, offline HTML 5 applications, and sophisticated client-side toolkits like GWT. It's based on the following observations:
Anything might need to happen asynchronously, so design everything to be asynchronous from the very beginning.
Testing browser-based views is much slower than testing models and presenters.
Your real model data lives on the server, but you may have a local cache or an offline HTML 5 database.
In this approach:
The view is very dumb, and you can replace it with mock objects when running unit tests.
The model objects are just simple containers for data, with no real logic. You may have multiple model objects representing the same entity.
The presenter listens to events from the view. Whenever it needs to update or read from the model, it sends an asynchronous message to the server (or to a local caching service). The server responds by sending events to the "event bus". These events contain copies of the model objects. The event bus passes these events back to the various presenters, which update the attached views.
So this architecture is inherently asynchronous, it's easy to test, and it doesn't require major changes if you want to write an HTML 5 offline application. I haven't used it yet, but it's next on my list of things to try. :-)
Both MVP and MVC make sense and allow to separate logic from display.
I would choose MVC because it's widely used in web development these days (Rails, .NET MVC which is used for SO) so my application will be more easily maintainable by someone else. It is also -to me- cleaner (less "power" given to the view), but this is subjective.
Another alternative is MTV, Model-Template-View which Django uses.

Resources