In another question, someone told me to implement the following in my java program. But, I am very new to Java and I do not know how to start to convert my simple program into this structure:
Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
dependency injection.
program to the interface:
Does that come inside some framework? Should I start learning Spring and this structure will evolve naturally? Or, can I implement above technologies one by one without using a framework?
You can implement them without a framework if you wish, but you give up whatever benefits the framework offers you.
The layering you cite is correct and independent of any framework; it's just programming to interfaces and separation of concerns. You're free to do it without Spring if you wish to minimize the number of new technologies you want to learn right now.
If you don't know what persistence is, then you shouldn't jump into Spring. Persistence means storing data in relational databases using SQL to most people. If you don't know that, I'd recommend starting there.
All the patterns books in the world won't help you if you've never used the underlying technologies.
If you've never done any of this, I'd recommend sticking to straight JDBC, servlets, and JSPs using only JSTL (no scriptlets). Anything beyond that will just be confusing.
If you had a Foo model object, with persistence, service, and view tiers, the interfaces might look like this:
package model;
/**
* A model object that's interesting from your problem's point of view
*/
public class Foo
{
}
package persistence;
/**
* CRUD operations for a Foo
*/
public interface FooDao
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package service;
/**
* Just a data service that wraps FooDao for now, but other use cases would
* mean other methods. The service would also own the data connection and manage
* transactions.
*/
public interface FooService
{
Foo find(Long id);
List<Foo> find();
void saveOrUpdate(Foo foo);
void delete(Foo foo);
}
package view;
/**
* A class that owns services, validates and binds input from UI, and handles routing
* to the next view once service is complete.
*/
public interface FooController
{
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response);
}
These are just interfaces, of course. You'll need to provide implementations.
You might want to check out Domain Driven Design. The Code samples are in Java. The things you listed are design related more than any specific technology.
In short:
Data Access Layer is a module of your application that provides interface to your data. Data may be in SQL database, XML, file wherever. You write interfaces and classes that provide interface to access data usually as VO or DTO via DAOs
Service Layer contains most of the use-case logic. Service layer interacts with Data Access Layer to perform tasks in given use case. I did not find a good article on introductory service layer. You may see here and there
Controller is the one that interacts with Service Layer and/or Data Access Layer and/or other controllers in order to perform a specified client's tasks. For example, a sign-off button controller will request a sign-off action/service to invalidate user's sessions on all services that user is logged on to, then it will choose an appropriate view or log-off web-page to forward user to.
Presentation is your user interface. It can be a web-page made of HTML or Java Swing window or anything that user interacts with. GUI commonly known term for it. This is what your users will be interacting with using mouse clicks, scrolls, swipes, drag-and-drop. These actions are mapped with controller which performs action based on what user performed on UI.
Dependency Injection is a way to wire various components. There are a lot of resources on web. You can look in Martin Fowler's this article. It's basically a mechanism that allows components to behave much like plug-and-play devices, if you know what plug goes where.Spring is a good implementation of dependency injection. You may not want to write your own framework, and at this stage, you should rather not. There is a Spring MVC framework that can do things for you.
But I suggest you start from very basic. Instead of jumping on jargon, read from basic. Start with a good book on application development using Java. You can also look into
Design Patterns - Gang of Four
Core J2EE Patterns
Developing a Spring Framework MVC application step-by-step
dependency Injection with the Spring Framework
You can implement all of this is you want -- it's been done many times before, but nothing prevents you from doing it again.
What would be a better use of your time is to make sure you understand the separation of concerns you listed above (which are generally right) and identify the most efficient integration of existing frameworks to leverage (e.g., Hiberante, Spring, Guice, etc). There are multiple answers for that one (and no shortage of opinions!), but all things being equal, the less frameworks you have to integrate, the easier and better fitting it's likely to be.
Spring has a very well known framework which covers many of these things, so it would be wise to start there. It also allows you to work with other frameworks (i.e., you can use selective parts of Spring). For example, you can use Spring for dependency injection and use a different MVC framework.
It is very hard to answer this question. First of all, I don't know what your program looks like. Second, I don't think 'converting' it is something that can be done, or should be done for that matter. What you're talking about are architectural concepts that the developers usually have in mind while designign the application.
If these concepts interest you, I suggest reading a bit about Model-View-Controller pattern (MVC) and service-oriented Architecture (SOA).
These are general concepts that do not apply specifically to Java. However, they are widely used in Java enterprise development. Various frameworks allow you to create applications utilizing these concepts. For example, Spring Web MVC, as others have pointed out, is part of the Spring Framework that lets you create web applications that adhere to the MVC pattern.
If your program is really simple this separation might be done by using one calss for each
category.
Data Access Layer (read/write data) -> one class for presisting laoding
Service Layer (isolated business logic) -> one calss with bussiness logic
Controller (Link between view and model) -> in simple swing app this merges with UI
Presentation (UI) -> one class for one widnow
dependency injection -> not used in small apps
program to the interface -> Your service class should use interface tah is used by other class instead of directly your serivce implementation:
if it's not as simple program you might want to have package for each category.
BUT - don't overdesign! These concepts are ment to help you manage large scale applications, not to ruin you in your programming begginigs!
Related
I have been trying to figure out which layer between the Model and Controller loads data from a text file.
I want to write a load method which loads a person's information from text file info.txt which stores the person information
I have a Person class ( model) and PersonController class (controller)
My question is, using the MVC design, where should I write the Load method?
Thank You
In MVC, the responsibility to load data is in ... nowhere really. The controller should call something else that does the persistence. In fact, in a well organised app, it should call something that ends up calling the class that loads/stores data.
From Wikipedia
Model–view–controller is a software design pattern commonly used for developing user interfaces [...]
So MVC helps to deal with the user-interface, but the core of your application, has to be built using a different pattern. The one I've used in the last ~10 years, and which I think it's quite alright, is Ports-and-Adapters (also called Hexagonal Architecture).
Links (from Alistair Cockburn wiki)
https://wiki.c2.com/?PortsAndAdaptersArchitecture
https://wiki.c2.com/?HexagonalArchitecture
If you can, get a copy of "Growing Object-Oriented Software guided by tests". It's an amazing book and has a very clear explanation of these ideas.
I am trying to create a graphical flashcards app from scratch. I have a few questions:
a. I have used Swing to build some apps in the past, calculator app. But I felt that was a trivial application so I want to ramp up my skills as a Java developer.
b. I have been told that a gold standard is to build a small application that uses one of these: MVC, MVM, MVVM and so on.And since I am learning design patterns, I was hoping to use it in the application.
c. My classes are such:
A model: Flashcard.java(It has a list of answers, a list of
pictures, a question), A FlashCard Manager(to perform CRUD)
Different view classes: GUI interface
Controller: All the event listeners
App: To initialize the app
d. I have tried to read online examples of such a combination and what was proposed in for the Manager or DAO, was to have it connect to JDBC for the database. I am trying to simulate that by using a HashMap> for the same purpose.Is that correct or do I have to use JDBC or SQLite?
e. Also am I supposed to have a controller-view pair, that is for every JComponent that uses an event listener or a controller for windows( startup window, main application window, child windows)?
f. Also should the controller class be an interface for all these controllers?
I do not have code because I am still developing it but I just wanted to get a general idea. Thanks for answering my questions.
b. I have been told that a gold standard is to build a small application that uses one of these: MVC, MVM, MVVM and so on.And since I am learning design patterns, I was hoping to use it in the application.
This both right and wrong. Some API's simply don't support the notion of a pure MVC (or variation). Swing for example implements a form of MVC of it's own which is more like M-VC, where the model is separate, but the view and controller are bound.
Think about a JButton. Do you ever apply a controller to it? You can add listeners to it, you can even add listeners directly to it's model, but it has it's own internal control mechanism, which generates events based on keyboard and mouse interaction.
You need to beware of when a MVC might not be suitable or where the amount of work to implement a pure MVC is not worth the effort.
Having said that, you can wrap Swing UI's in another MVC layer, but you need to think about it at a different level. Instead of each controller been considered a "view", you look at the container, which might contain multiple controls and see it as the "view", which a controller then manages.
d. I have tried to read online examples of such a combination and what was proposed in for the Manager or DAO, was to have it connect to JDBC for the database. I am trying to simulate that by using a HashMap> for the same purpose.Is that correct or do I have to use JDBC or SQLite?
This is not an unreasonable idea, however, you want to ensure that the public interface remains constant. This would allow you to change the implementation at a later date to use JDBC or a web service without having to rewrite the code that depends on it
e. Also am I supposed to have a controller-view pair, that is for every JComponent that uses an event listener or a controller for windows( startup window, main application window, child windows)?
This will depend. I tend to avoid exposing individual components, as this exposes them to unwanted modifications (you may not want a controller to be able to change the text of a button for example)
As a general rule of thumb, I try to make the relationship between the controller and the view as vanilla as possible, meaning that the controller shouldn't care about how the view is implemented, only that it upholds the contract between the it subscribes to.
This generally means I have a functional view, which is contracted to produce certain events/data and allows certain interaction (from the controller)
f. Also should the controller class be an interface for all these controllers?
IMHO, yes. This allows a view/controller/model to be implemented differently, but allows the rest of the code to continue working with it without the need to be modified.
The bottom line is, implementing a MVC over Swing is not as simple as people think it is. It takes some planning and consideration, but it is doable.
For a more detailed example, have a look at Java and GUI - Where do ActionListeners belong according to MVC pattern?
Ideally, controllers in a Spring MVC application must receive a request, despatch the request to an API, load the results (of the invocation) on to the model (for the view to subsequently render it) and forward to a view. They should do no more.
My controllers do far more than this today and I would like to move certain resposibilities away from the controller on to other APIs. My application design today (pretty typical):
controller <-> Service API <-> DAO <-> DB
The controller today fills up the delta between what the web app needs and what the Service API delivers.
I would like to place extra layer/layers between the controller and service API that chew away at this delta. My question is what layer(s) should these be and what should the responsibilities of these new layer(s)?
My current Idea is as follows
controller <-> controller helper <-> Business API <-> Service API <-> DAO <-> DB
Controller helper (web context aware - will depend on Model, HttpServlet and other web context classes):
Convert entities to DTO objects (2 way)
Resolve IDs to entities. E.g. Controller looks up a student i.d. (using a key) and converts it to a Student entity.
Business API (no web context dependency - can be JUnit tested):
Acts as a Facade. Invoking multiple service APIs to achieve one
business request.
Providing APIs that are specifically tailered for the web app.
Would you solve this a different way? Are there any resources (books, articles etc...) relating to this specific issue?
Some of previous discussions that did not answer my question:
Designing mvc controller layer
Service layer = Application layer = GRASP Controller layer
Moving Validation, Html Helpers to Service Layer in MVC
Thanks,
Vijay
Services contain the general business logic of an application. They are pretty much anything between Controllers and DAO/DB.
Your "business layer" and "controller helper" are just more services. I would keep the classic design for the sake of simplicity :
Controllers <-> possible Services <-> possible DAOs <-> DB
If I had lots of services (I usually don't) that happened to perform the same kind of logic, I would naturally split them into sub-packages. For example :
services.facade, or services.business
services.adapter for DTOs (except if you use simple classes to do this job)
A facade service is called by controllers like so : someFacade.someMethod(SomeDTO someDto). Then the facade handles DTO <-> Entity conversion thanks to other services (or simple classes).
That's how I would do in your context. In an ideal world (no legacy systems, or in a project from scratch), I'd directly use entities as form objects (instead of DTOs), and most of my services would be facades (the rest would be simple classes, if possible).
I'm new to Spring MVC and am also faced with this dilemma. Although Spring is new to me, I've been working with MVC for several years. I agree a controller should do no more than accept requests, dispatch them, and render the results in the correct format. I'm of the opinion that a service isn't necessarily the best place for the helper abstraction to exist though. I believe a service should encapsulate a specific API and do nothing more. I feel creating many 'types' of services convolutes this pattern and makes it unclear where the responsibilities fall.
It's my belief that helpers are better suited as siblings to services; they should be decorated with #Component instead of #Service. Their role is to act as a facade for the underlying APIs that are needed to transition state on the models exposed through the endpoint. The Controller->Helper->[Services] pattern promotes a clear separation of concerns, code-reusability, and is highly testable. The nature of this pattern is to prevent controller bloat, so you end up with ultra-thin controllers that really do nothing more than dispatch requests and render responses.
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
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