Do AOP violate layered architecture for enterprise apps? - spring-mvc

The question(as stated in the title) comes to me as recently i was looking at Spring MVC 3.1 with annotation support and also considering DDD for an upcoming project. In the new Spring any POJO with its business methods can be annotated to act as controller, all the concerns that i would have addressed within a Controller class can be expressed exclusively through the annotations.
So, technically i can take any class and wire it to act as controller , the java code is free from any controller specific code, hence the java code could deal with things like checking security , starting txn etc. So will such a class belong to Presentation or Application layer ??
Taking that argument even further , we can pull out things like security, txn mgmt and express them through annotations , thus the java code is now that of the domain object. Will that mean we have fused together the 2 layers? Please clarify

You can't take any POJO and make it a controller. The controller's job is get inputs from the browser, call services, prepare the model for the view, and return the view to dispatch to. It's still a controller. Instead of configuring it through XML and method overrides, you configure it through annotations, that's all.
The code is very far from being free from any controller specific code. It still uses ModelAndView, BindingResult, etc.

I'll approach the question's title, regarding AOP:
AOP does not violate "layered architecture", specifically because by definition it is adding application-wide functionality regardless of the layer the functionality is being used in. The canonical AOP example is logging: not a layer, but a functionality--all layers do logging.
To sort-of tie in AOP to your question, consider transaction management, which may be handled via Spring's AOP mechanism. "Transactions" themselves are not specific to any layer, although any given app may only require transactions in only a single layer. In that case, AOP doesn't violate layered architecture because it's only being applied to a single layer.
In an application where transactions may cross layers IMO it still doesn't violate any layering principles, because where the transactions live isn't really relevant: all that matters is that "this chunk of functionality must be transactional". Even if that transaction spans several app boundaries.
In fact, I'd say that using AOP in such a case specifically preserves layers, because the TX code isn't mechanically reproduced across all those layers, and no single layer needs to wonder (a) if it's being called in a transactional context, or (b) which transactional context it's in.

Related

How to introduce application-wide context object?

I need to make several properties accessible from application's business layer. Those are some ids and common settings. Most of them are valid only through request-response lifespan.
This is a web application (ASP.NET Web Forms to be specific) with dependency injection set up.
Currently those properties are passed through method parameters directly to business layer's services. That works but is not very efficient since:
sometimes parameters' values need to be passed deeper obscuring the readability a bit
some properties should be lazy resolved, and this should be done only once per request
retrieving properties which are resolved by touching a database can be confusing for new developers (there is not unified way of doing this)
some services are constructed by a factory which enriches them with some config parameters
I was thinking about introducing an application context interface, with an implementation in the main project, which would be created on every request. It could be injected to the services directly making them parametrized automatically and independently (services won't need the factory anymore).
Is it how this problem should be tackled or maybe there are some other options?
One option I don't like here is that it might bond the main particle with business layer which is not a perfect example of The Clean Architecture.
Id say you solution is a very common one - inject an 'application context' into your classes. One thing I would be careful of though is making sure you are following the Integration Segregation Principle (from SOLID). Dont just start making all your classes expect an application context instance. Instead, design interfaces that split the application context up, and have your classes expect them as dependencies. Your application context will then need to implement all the interfaces.
This is the correct way to do things as it decouples your classes from implementation. Really your classes don't care if their dependency is from one giant application context, they just care about specific methods implemented by it. This will make your code more robust as you will reduce the risk of breaking something if you change the implementation of the application context later on.
Why don't you use some dependency injection container? Your global settings and parameters can be registered to it as pseudo-singletons and then you will be able to neatly request them from any point inside your application.

How to avoid session-related parameters in business layer?

I have a Java EE application (simple web GUI, a large EJB 3 business layer, JPA) whose most functions depend on the currently logged-on user.
Because of this, the EJBs are infested with omnipresent String userName parameter. You can hardly find a non-trivial method that goes without it, and it descends all the way down to the most basic EJBs. Occasionally it is supplemented by other session-related parameters, like user's locale.
As a result, parameter lists grow and code clarity suffers. It's probably a common problem, how to avoid it? Pushing more code to the GUI client seems even crazier idea.
Java EE has support for security context propogation across various layers. For e.g. checkout various methods on the EJBContext related to authentication/authorization such as getCallerPrincipal(), isCallerInRole(). I suggest you read the below two articles
High level introduction to end to end security
Introduction to Security in the Java EE Platform

Why use facade pattern in EJB?

I've read through this article trying to understand why you want a session bean in between the client and entity bean. Is it because by letting the client access entity bean directly you would let the client know exactly all about the database?
So by having middleman (the session bean) you would only let the client know part of the database by implementing the business logic in some certain way. So only part of the database which is relevant to the client is only visible. Possibly also increase the security.
Is the above statement true?
Avoiding tight coupling between the client & the business objects, increasing manageability.
Reducing fine-grained method invocations, leads to minimize method invocation calls over the network, providing coarse-grained access to clients.
Can have centralized security & transaction constraints.
Greater flexibility & ability to cope with changes.
Exposing only required & providing simpler interface to the clients, hiding the underlying complexity and inner details, interdependencies between business components.
The article you cite is COMPLETELY out of date. Check the date, it's from 2002.
There is no such thing anymore as an entity bean in EJB (they are currently retained for backwards compatibility, but are on the verge of being purged completely). Entity beans where awkward things; a model object (e.g. Person) that lives completely in the container and where access to every property of it (e.g. getName, getAge) required a remote container call.
In this time and age, we have JPA entities that are POJOs and contain only data. Don't confuse a JPA entity with this ancient EJB entity bean. They sound similar but are completely different things. JPA entities can be safely send to a (remote) client. If you are really concerned that the names used in your entity reveal your DB structure, you could use XML mapping files instead of annotations and use completely different names.
That said, session beans can still perfectly be used to implement the Facade pattern if that's needed. This pattern is indeed used to give clients a simplified and often restricted view of your system. It's just that the idea of using session beans as a Facade for entity beans is completely outdated.
It is to simplify the work of the client. The Facade presents a simple interface and hides the complexity of the model from the client. It also makes it possible for the model to change without affecting the client, as long as the facade does not change its interface.
It decouples application logic with the business logic.
So the actual data structures and implementation can change without breaking existing code utilizing the APIs.
Of course it hides the data structure from "unknown" applications if you expose your beans to external networks

The Purpose of a Service Layer and ASP.NET MVC 2

In an effort to understand MVC 2 and attempt to get my company to adopt it as a viable platform for future development, I have been doing a lot of reading lately. Having worked with ASP.NET pretty exclusively for the past few years, I had some catching up to do.
Currently, I understand the repository pattern, models, controllers, data annotations, etc. But there is one thing that is keeping me from completely understanding enough to start work on a reference application.
The first is the Service Layer Pattern. I have read many blog posts and questions here on Stack Overflow, but I still don't completely understand the purpose of this pattern. I watched the entire video series at MVCCentral on the Golf Tracker Application and also looked at the demo code he posted and it looks to me like the service layer is just another wrapper around the repository pattern that doesn't perform any work at all.
I also read this post: http://www.asp.net/Learn/mvc/tutorial-38-cs.aspx and it seemed to somewhat answer my question, however, if you are using data annotations to perform your validation, this seems unnecessary.
I have looked for demonstrations, posts, etc. but I can't seem to find anything that simply explains the pattern and gives me compelling evidence to use it.
Can someone please provide me with a 2nd grade (ok, maybe 5th grade) reason to use this pattern, what I would lose if I don't, and what I gain if I do?
In a MVC pattern you have responsibilities separated between the 3 players: Model, View and Controller.
The Model is responsible for doing the business stuff, the View presents the results of the business (providing also input to the business from the user) while the Controller acts like the glue between the Model and the View, separating the inner workings of each from the other.
The Model is usually backed up by a database so you have some DAOs accessing that. Your business does some...well... business and stores or retrieves data in/from the database.
But who coordinates the DAOs? The Controller? No! The Model should.
Enter the Service layer. The Service layer will provide high service to the controller and will manage other (lower level) players (DAOs, other services etc) behind the scenes. It contains the business logic of your app.
What happens if you don't use it?
You will have to put the business logic somewhere and the victim is usually the controller.
If the controller is web centric it will have to receive its input and provide response as HTTP requests, responses. But what if I want to call my app (and get access to the business it provides) from a Windows application which communicates with RPC or some other thing? What then?
Well, you will have to rewrite the controller and make the logic client agnostic. But with the Service layer you already have that. Yyou don't need to rewrite things.
The service layer provides communication with DTOs which are not tied to a specific controller implementation. If the controller (no matter what type of controller) provides the appropriate data (no mater the source) your service layer will do its thing providing a service to the caller and hiding the caller from all responsibilities of the business logic involved.
I have to say I agree with dpb with the above, the wrapper i.e. Service Layer is reusable, mockable, I am currently in the process of including this layer inside my app... here are some of the issues/ requirements I am pondering over (very quickly :p ) that could be off help to youeself...
1. Multiple portals (e.g. Bloggers portal, client portal, internal portal) which will be needed to be accessed by many different users. They all must be separate ASP.NET MVC Applications (an important requirement)
2. Within the apps themselves some calls to the database will be similar, the methods and the way the data is handled from the Repository layer. Without doubt some controllers from each module/ portal will make exactly or an overloaded version of the same call, hence a possible need for a service layer (code to interfaces) which I will then compile in a separate class project.
3.If I create a separate class project for my service layer I may need to do the same for the Data Layer or combine it with the Service Layer and keep the model away from the Web project itself. At least this way as my project grows I can throw out the data access layer (i.e. LinqToSql -> NHibernate), or a team member can without working on any code in any other project. The downside could be they could blow everything up lol...

Controllers != Business Layer?

So I'm assuming people still use a business layer outside just controller logic? If so where's that grey line drawn and what do you not put in your controller classes that you would in your Business Layer project and vice versa? Seems to me like Controllers rid the need for a business layer in your MVC application totally.
The controller layer is part of the view, in my opinion. What you're calling the business layer I call services (not web services; that's just one deployment choice among many).
The business layer knows about use cases and units of work for accomplishing the objectives of users.
The controller is all about validating, binding, and marshaling requests, determining which service is needed to fulfill the request and passing values to it, unmarshaling the response and routing it to the next appropriate view.
So I agree with the hypothesis posed in your title: controller != service.
The classic pattern that came from Smalltalk is Model-View-Controller, which disagrees with my statement by breaking view and controller into separate tiers.
What I'm describing is what is implemented in Java frameworks for both web and desktop. A change in view technology generally means changing the controller as well.
So if the Smalltalk idiom was model-view-controller, the more modern approach would look like view->controller->service->model/persistence. Model means "domain objects", which are independent of all view technologies.
The line is not "grey". It's stark and absolute.
The model (or "business layer") works with any presentation. GUI, command-line, web. And it doesn't require any changes to be wrapped with a GUI (view+control) a Command-line application or a web application.
You know you've done the model ("business layer") correctly when there are no presentation or control features in at all. Further, it's so complete that any GUI can use it directly.
To put it simply:
Controller should contain the application specific logic.
"Business Layer" should contain the business logic.
Following Eric Evans' Domain Driven Approach, the "Business Layer" contains:
Service tier: the interface is designed around the use case scenario
Domain Models: the core domain objects, entities, value objects and more.
Data Access objects: repositories
Also note that the Domain models is not the Data Access tier. It might encapsulate data access, but is not the data access tier itself.

Resources