How does the Three Tier architectural style works? Some handy example - java

I have been provided with a Java Application on which to apply the Three-Tier architectural style; One of the use cases to do is the login.
I've studied all the theory and rules that apply to this architectural style, but I need to understand the logic of the objects co-operation between the various levels and how patterns work together on each level to realize this (and the others) use case.
First, I've created the three basical packages: Presentation, Application and Data. In addition, I included one more package about the Boundary classes, The various GUIs from which requests will be sent.
In the Presentation layer, I just put a Front Controller, that encapsulates the presentation logic required by clients using the application.
In the Data layer, I put a DatabaseConnection class (Class that communicates with the database and that is responsible for loading the driver, connecting to the database, querying etc.) and DAOs classes (Data Access Object, that interfaces with the database).
The real problem is that I don't know what to put in the Application level, which represents the main part of the application, defining the domain model of the application, that is: their entities, their relationships, and application logic. It should not contain any reference to how the data will be presented to the user or how they will be saved.
So, I currently have this hierarchy:
Main ---> Boundary > Presentation > Application > Data > Database
In accordance with this architecture, how can I make a simple login?
Bearing in mind that each level can communicate ONLY with the underlying level;
For example, a class in Boundary layer cannot comunicate directly with a class in Data layer, Boundary's classes can comunicate with Presentation's classes only.
If necessary, you can post a pseudocode, which makes the idea of the steps to do.

Your Boundary calls only basic methods on the Presentationlayer.
Let's say the User clicks a Button to create a User the flow would be the following: Boundary calls method createUser(String name, int age) on the FrontController (Presentationlayer). The Controller can check some basic (UI-Related) things and would then call a similar method on the Applicationlayer.
The Applicationlayer can now process some further checks (for example: is the Current Active User allowed to create a User?). The Applicationlayer takes the given informationen (name and age), creates a DAO based on that and invokes the method to create the User on the Datalayer (DAO).
The Datalayer simply inserts the given information.

Related

Rails application, but all data layer is using a json/xml based web service

I have a web service layer that is written in Java/Jersey, and it serves JSON.
For the front-end of the application, I want to use Rails.
How should I go about building my models?
Should I do something like this?
response = api_client.get_user(123)
User user = User.new(response)
What is the best approach to mapping the JSON to the Ruby object?
What options do I have? Since this is a critical part, I want to know my options, because performance is a factor. This, along with mapping JSON to a Ruby object and going from Ruby object => JSON, is a common occurance in the application.
Would I still be able to make use of validations? Or wouldn't it make sense since I would have validation duplicated on the front-end and the service layer?
Models in Rails do not have to do database operation, they are just normal classes. Normally they are imbued with ActiveRecord magic when you subclass them from ActiveRecord::Base.
You can use a gem such as Virtus that will give you models with attributes. And for validations you can go with Vanguard. If you want something close to ActiveRecord but without the database and are running Rails 3+ you can also include ActiveModel into your model to get attributes and validations as well as have them working in forms. See Yehuda Katz's post for details on that.
In your case it will depend on the data you will consume. If all the datasources have the same basic format for example you could create your own base class to keep all the logic that you want to share across the individual classes (inheritance).
If you have a few different types of data coming in you could create modules to encapsulate behavior for the different types and include the models you need in the appropriate classes (composition).
Generally though you probably want to end up with one class per resource in the remote API that maps 1-to-1 with whatever domain logic you have. You can do this in many different ways, but following the method naming used by ActiveRecord might be a good idea, both since you learn ActiveRecord while building your class structure and it will help other Rails developers later if your API looks and works like ActiveRecords.
Think about it in terms of what you want to be able to do to an object (this is where TDD comes in). You want to be able to fetch a collection Model.all, a specific element Model.find(identifier), push a changed element to the remote service updated_model.save and so on.
What the actual logic on the inside of these methods will have to be will depend on the remote service. But you will probably want each model class to hold a url to it's resource endpoint and you will defiantly want to keep the logic in your models. So instead of:
response = api_client.get_user(123)
User user = User.new(response)
you will do
class User
...
def find id
#api_client.get_user(id)
end
...
end
User.find(123)
or more probably
class ApiClient
...
protected
def self.uri resource_uri
#uri = resource_uri
end
def get id
# basically whatever code you envisioned for api_client.get_user
end
...
end
class User < ApiClient
uri 'http://path.to.remote/resource.json'
...
def find id
get(id)
end
...
end
User.find(123)
Basic principles: Collect all the shared logic in a class (ApiClient). Subclass that on a per resource basis (User). Keep all the logic in your models, no other part of your system should have to know if it's a DB backed app or if you are using an external REST API. Best of all is if you can keep the integration logic completely in the base class. That way you have only one place to update if the external datasource changes.
As for going the other way, Rails have several good methods to convert objects to JSON. From the to_json method to using a gem such as RABL to have actual views for your JSON objects.
You can get validations by using part of the ActiveRecord modules. As of Rails 4 this is a module called ActiveModel, but you can do it in Rails 3 and there are several tutorials for it online, not least of all a RailsCast.
Performance will not be a problem except what you can incur when calling a remote service, if the network is slow you will be to. Some of that could probably be helped with caching (see another answer by me for details) but that is also dependent on the data you are using.
Hope that put you on the right track. And if you want a more thorough grounding in how to design these kind of structures you should pick up a book on the subject, for example Practical Object-Oriented Design in Ruby: An Agile Primer by Sandi Metz.

MVC with DAO/VO - Which DAO should the Controller talk to?

Background:
I have a design pattern problem that I was hoping someone may be able to solve. I program in PHP but I believe DAO/VO is popular in Java.
I have been using MVC for many years now. I designed a shopping that was MVC but used procedural programming. Thus recently I decided to develop the cart again, using OO.
Problem:
The problem I was faced with was that my Product class did not make sense to have a RetrieveAll() method.
E.g. If I had 10 products listed, from which instance would I call the RetrieveAll() method? I would have 10 choices.
Solution:
Thus, I found the DAO/VO pattern.
Unless I have not researched this pattern enough - I believe that each DB table must have a Model + DAO. No model or DAO should know about another set of models or DAO's. Thus being encapsulated.
The pattern makes perfect sense, pulling the database layer away from the Model.
However. In the shopping cart, my products are assigned categories.
A category could be electronics, clothing, etc.
There are 3 tables:
- Category (pid, name)
- Category Item (iid, name)
- Category Link (pid, iid)
From an MVC approach, it doesn't make sense of which DAO the controller should be talking to?
Should it be:
The controller talks to all 3 DAO's and then return the appropriate data structure to the View?
Or should the DAO's talk to one-another (somehow) and return a single structure back to the Controller?
Please see here for example (image)
I'm not sure what do you mean by VO. Is it value object?
I'm a huge fan of the DDD (domain driven design) approach (though I don't consider my self as guru in it). In DDD you have so called Services. Service Is an action that operates on your domain and returns data. Service encapsulates the manipulation with you Domain data.
Instead of having the controller to do all the domain logic like what items to retrieve, what DAO's to use and etc (why controller should care about the Domain anyway?), it should be encapsulated inside the Domain it self, in DDD case inside a Service.
So for example you want to retrieve all the Category items of the category "electronics".
You could write a controller that looks like this (forgive me if the code have invalid syntax, its for the sake of example):
public function showItemsByCategoryAction($categoryName) {
$categoryId = $categoryDAO->findByName($categoryName);
if(is_null($categoryId)) {
//#TODO error
}
$itemIds = $categoryLinkDAO->getItemsByCategoryId($categoryId);
if(empty($itemIds)) {
//#TODO show error to the user
}
$items = $categoryItemDAO->findManyItems($itemIds);
//#TODO parse, assign to view etc
}
This introduces at least two problems:
The controller is FSUC (Fat stupid ugly controller)
The code is not reusable. If you would like to add another presentation layer (like API for developers, mobile version of the website or etc), you would have to copy-paste the same code (expect the part of the view rendering), and eventually you will come to something that will encapsulate this code, and this is what Services are for.
With the Services layer the same controller could look like
public function showItemsByCategoryAction($categoryName) {
$service = new Item_CategoryName_Finder_Service();
$items = $service->find($categoryName);
if(empty($items)){
//#TODO show empty page result, redirect or whatever
}
$this->getView()->bind('items', $items);
}
The controller is now clean, small, and all the Domain logic is encapsulated inside a service that can be reused anywhere in the code.
Now some people believe that the controller should know nothing about DAOs and communicate with the Domain only by using Services, other says that its ok to make calls to DAOs from the controller, there are no strict rules, decide what suits better for you.
I hope this helps you!
Good luck :)
I'm not an expert in DDD either , but this is my opinion. This is the situation where the repository patern is applied. Basically, the Domain doesn't know nor care about DAO or anything else rpesistence related. At most knows about the repository inteface (which should be implemented at the infrastructure level).
The controller knows about the domain and the repository. The repository encapsulates everything db related, the application knows only about the repository itself (in fact the interface as the actual implementation should be injected). Then within the repository you have DAOs however you see fit. The repository receives and sends back only application/domain objects, nothing related to db acess implementation.
In a nutshell, anything db related is part and it's an implementation detail of the repository.
return type can be considered when deciding which dao method should go to which dao class, hence which dao should the controller talk to:
Implement one DAO class per Data Entity is more cleaner,
CRUD operations should go in to Dao classes,
C-Create, R-Read, U-Update, D-Delete
Read operations are not like Create, Update, Delete, most of the time Read operations have different flavors when considering what they return.
for Read operations, return type can be considered when deciding which dao method should go to which dao class
following are some Business Entities and there Dao
Exchange -> ExchangeDao
Company -> CompanyDao
Stock -> StockDao

MVC architectural pattern

I have been doing Java and Ruby (and used frameworks) for some while and I know MVC is a way to separate code. The thing is, I think I never really used it in the way it should.
The first question is: Business logic, what does it mean? Does Business logic mean the logic that is special for that application? Let say you are building a Satellite system. Is the business logic the code that is unique for that Satellite system and make it work?
What does "domain" mean? Like in domain logic or domain as a term.
"Keep your model smart, controllers thin and view dumb". This statement clearly indicates that the controllers which I load with too much code is the wrong way of writing it.
As an example. If you have a BankAccount class. Then should this class provide methods for behavior such as validating etc as well as getter/setter?
What should the controller be doing? Just redirecting input/events in the view to the model and maybe update view (which is the case in webframeworks).
For example in Java and JPA you have the entityManager that you use for finding entities, maybe do something on them etc. Should this entitymanager be used in the controller, or should you make another layer named e.g. "Service" which the controller uses. But again, does this server layer then belong to the Model in MVC? How would you do this in Rails?
I don't get the Model nor the Controller concept right I think.
Think of applications as being layered. When working on each layer, always think to yourself, "Is this layer dependent on the layer above it or can it work independently?" That is the basis to a good MVC application.
When thinking of layers in an MVC style application, there are a few.
In my mind the layers (from top to bottom) are the view, controllers, business logic, and data access.
The view could be JSP or even AJAX requests from jQuery. This is where the user interacts with your application. The view sends information to the business logic layer to do work.
Controllers should be written to collect data sent to it from the view, transform it in a way that the business logic can understand it, and then pass the information into the business logic layer. Controllers may also take information retured from the business logic layer, transform it, and send it back to the view. No real "business logic" should happen here. Think of it as a broker between the view and the business object layer. This is also a great spot for validating data submitted by the view.
Business logic is a layer you would find in the middle, typically between the controllers and data access layer. This could also be called a service layer. It should be written to not know anything about what is calling it. If written correctly, you could use this layer in a standalone application. Here is where a lot of the application smarts should take place. A lot of times, this layer is simply here to call the data access layer and return the results back to the controllers. But, a lot of other things could go on here like data manipulation, calculations, data security, validation, etc.
The data access layer should be written in such a way that it takes it's input, retrieves the appropriate data, transforms it into a useable form, and returns it. This layer should not know or care what is calling it and should be written in that way. Again, this layer should not know it is in a web application or a stand alone application. There are a lot of options here to make your life simpler in the form or ORM (Object Relational Mapping) frameworks. If your application is a step above trivial, you should think about using one.
In the traditional sense, the model could be the business logic layer and the data access layer as well as the domain objects that go along with them.
Using "BankAccount" as an example:
"BankAccount" sounds more like a domain object (representation of data in a database) than a class that has logic in it. Typically domain objects only have the fields they need (account number, balance, etc.) with getters and setters.
The user might log into their bank website. On login, the view sends the username to the controller (BankAccountController). The controller takes this information out of the request and sends it to the service layer (BankAccountService). The service layer would send this information to the data access layer which does a query for the BankAccounts that the user might have and return them to the service layer which returns them to the controller. The controller will manipulate this information in some way that the view layer can display them to the user. There would be a similar series of events when the user transfers money between accounts, for instance.
Hope this helps... let me know if you have any more questions or if something isn't clear.
Edit:
Besides the links posted by the other users, Wikipedia has a brief, but pretty good article on MVC.
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

On properly implementing complex service layers

I have the following situation:
Three concrete service classes implement a service interface: one is for persistence, the other deals with notifications, the third deals with adding points to specific actions (gamification). The interface has roughly the following structure:
public interface IPhotoService {
void upload();
Photo get(Long id);
void like(Long id);
//etc...
}
I did not want to mix the three types of logic into one service (or even worse, in the controller class) because I want to be able to change them (or shut them) without any problems. The problem comes when I have to inject a concrete service into the controller to use. Usually, I create a fourth class, named roughly ApplicationNamePhotoService, which implements the same interface, and works as a wrapper (mediator) between the other three services, which gets input from the controller, and calls each service correspondingly. It is a working approach, though one, which creates a lot of boilerplate code.
Is this the right approach? Currently, I am not aware of a better one, although I will highly appreciate to know if it is possible to declare the execution sequence declaratively (in the context) and to inject the controller with and on-the fly generated wrapper instance.
Also, it would be nice to cache some stuff between the three services. For example, all are using DAOs, i.e. making sometimes the same calls to the DB over and over again. If all the logic were into one place that could have been avoided, but now... I know that it is possible to enable some request or session based caching. Can you suggest me some example code? BTW, I am using Hibernate for the persistence part. Is there already some caching provided (probably, if they reside in the same transaction or something - with that one I am totally lost)
The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction. It sounds like you are mixing service classes when they could be in the same class and method. You can inject service classes into one another when required too, rather than create another "mediator".
It is perfectly acceptable to "mix the three types of logic", in fact it is preferable if they form an expected use case/unit of work
Cache-ing I would look to use eh cache which is, I believe, well integrated with hibernate.

Have I implemented a n-tier application with MVC correctly?

Being pretty unfamiliar with design patterns and architecture, I'm having trouble explaining to others exactly how my latest application is designed. I've switched between thinking it's a pure n-tier, pure MVC and n-tier with MVC in the presentation layer. Currently I think the latter is correct, but I want thoughts from more experienced developers.
How it works:
Browser sends HTTP request to Tomcat. Maps the request via web.xml to a servlet (which I call controller)
The controller instantiates one or more business object and calls methods on these, i.e. customerBO.getById(12) which again will perform business logic/validation before calling one or more DAO methods, i.e. customerDAO.getById(12). The BO returns a list of CustomerVO's to the controller
The controller prepares attributes for the view (JSP) (request.setAttribute("customers", customers);) and chooses a .jsp file to use which in turn will iterate the list and render XHTML back to the browser.
Structure (my proposal/understanding)
Presentation tier: currently using what I think is a MVC web-implementation: servlets (controllers), jsp (views) and my own implementation of OO XHTML forms (ie. CustomerForm) lies here. It should be possible to use a Swing/JavaFX/Flex GUI by switching out this presentation layer and without the need to change anything on the layers below.
Logic tier: Divided into two layers, with Business Objects (BO) on top. Responsible for business logic, but I haven't found much to put in here besides input validation since the application mostly consists of simple CRUD actions... In many cases the methods just call a method with the same name on the DAO layer.
DAO classes with CRUD methods, which again contacts the data tier below. Also has a convertToVO(ResultSet res) methods which perform ORM from the database and to (lists of) value objects. All methods take value objects as input, i.e. customerDAO->save(voter) and return the updated voter on success and null on failure.
Data tier: At the bottom data is stored in a database or as XML files. I have not "coded" anything here, except some MySQL stored procedures and triggers.
Questions (besides the one in the title):
The M in MVC. I'm not sure if I can call this n-tier MVC when the models are lists/VO's returned from business objects in the logic tier? Are the models required to reside within the presentation layer when the controller/view is here? And can the form templates in the presentation layer be called models? If so; are both the forms and lists from BO to be considered as the M in MVC?
From my understanding, in MVC the view is supposed to observe the model and update on change, but this isn't possible in a web-application where the view is a rendered XHTML page? This in turn leads me to the question: is MVC implemented differently for web-applications vs. regular desktop applications?
I'm not using a Front Controller pattern when all HTTP requests are explicitly mapped in web.xml right? To use Front Controller I need to forward all requests to a standard servlet/controller that in turn evalutes the request and calls another controller?
The Business Layer felt a little "useless" in my application. What do you normally put in this layer/objects? Should one always have a business layer? I know it should contain "business logic", but what is this exactly? I just perform input validation and instantiate one or more DAOs and calls the appropriate methods on them...
I realize there is MVC frameworks such as Struts for Java, but since this my first Java web-application I tried to get a deeper understanding of how things work. Looking in retrospect I hope you can answer some of the questions I stumbled upon.
I'm not sure if I can call this n-tier MVC when the models are lists/VO's returned from business objects in the logic tier
Those are perfectly good models. I also consider the ActionForms in Struts to be models. ActionForms are what Struts uses to represent/model HTML forms.
in MVC the view is supposed to observe the model and update on change, but this isn't possible in a web-application
Yep, and that is a matter of debate as to whether you can have true MVC with web-applications.
Should one always have a business layer?
It depends on the type of application. Some applications are database-driven, and are essentially a UI for the database. In that case, there's very little business logic required.
Data Tier:
The stored procedures aren't really part of the data tier code. You should be creating data access objects (DAOs) which are called by the business objects. The DAOs call the stored procedures. Further, the DAO interfaces should give no hint to the business objects as to where the data is stored, whether that be a database or file system or from some web service.
I think you are getting hung up in the terminology. The MVC pattern (I believe) pre-dates the classic web app arch you describe. It use to be that people called web app arch MVC 2 (Model 2 etc.) to differentiate it from the original MVC pattern...
see this link > http://www.javaranch.com/drive/servlet/#mvc2
HTH

Categories

Resources