Application Frameworks – How and Why

May 20th, 2010 Leave a comment 4 comments
Like the article?
Application Frameworks

Frameworks have become very popular for web development. There are frameworks available for almost every language including Ruby (Rails, Merb), Python (Django), Java (Spring, Hibernate), and PHP (Zend, CakePHP, Symfony). Most frameworks in use today enforce the model-view-controller (MVC) design pattern. This design pattern segments the code dealing with the database, the business logic and the user interface. Different frameworks include different sets of features, but they all have a number of common ways in which they operate. These common features provide a number of benefits to the developer working with a framework.

Models: Object Relational Mapping

One of the most basic problems when developing database driven web applications deals with persisting the state of code objects in a relational database. Code objects can have other objects as members and they have methods that may return the result of a calculation or procedure. The problem of how objects are represented in a relational database and how one stores, finds and retrieves these objects from a database is one of the core problems frameworks attempt to solve.

Most frameworks solve this problem through some sort of object relational mapping (ORM). An object relational mapping is a system of converting objects into relational data and relational data into objects. The model layer of most popular frameworks supplies an ORM that hides a lot of the raw SQL operations. This makes it possible for a developer to rapidly build a web application based on the abstract objects without worrying about building a database interface layer. Often, an ORM, will also abstract the database layer sufficiently that upgrading or transitioning from one database system to another is trivial. Here is an example of a MySQL Table represented as an ORM Java Class:

CREATE TABLE `car` (
  `id` int(11) NOT NULL auto_increment,
  `make` char(250) default NULL,
  `model` char(250) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

The equivalent ORM Java Class (Hibernate) would look like this:

package com.learncomputer.domain.Car;

public class Car {
	private Integer id;
	private String make;
	private String model;

	public Car(){
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getMake() {
		return make;
	}

	public void setMake(String make) {
		this.make = make;
	}

	public String getModel() {
		return model;
	}

	public void setModel(String model) {
		this.model = model;
	}

	public String toString() {
		return "Car: " + getId() + 
			" Make: " + getMake() + 
			" Model: " + getModel();
	}
}

Controllers: Business Logic

The controller layer of a framework is where most of the business logic for a web application resides. The controller interfaces with the models to determine what objects are needed to render a page and which templates should be used. Frameworks typically provide a number of useful helper functions to be used in the controller layer. These helpers typically perform tasks like extracting submitting form data, setting HTTP response codes and more. The controller layer can also be considered the input/output portion of a web application as this layer processes submitted data and prepares the data to return to the user.

Here is an example of a Spring MVC based controller:

package  com.learncomputer.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.learncomputer.domain.Car;
import com.learncomputer.service.CarService;

@Controller
@RequestMapping("/carRegistration.htm")
@SessionAttributes("car")
public class CarController {

	private CarService carService;

	@Autowired
	public void setCarService(CarService carService) {
		this.carService = carService;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String showCarForm(ModelMap model)  {
		Car car = new Car();
		model.addAttribute(car);
		return "carForm";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(@ModelAttribute("car") Car car) {
		carService.add(car);
		return "redirect:carRegistrationSuccess.htm";
	}
}

The @Controller annotation basically denotes this class as a “controller” class.

The @RequestMapping maps the request “/carRegistration.htm” to the CarController class.

The @SessionAttributes annotation stores the model object (car) in the session.

The onSubmit() method is triggered when a form for a adding a new car is submitted. After receiving the “car” object, the carService.add() method is called that processes the request and redirects the user to a success page.

Views: Templates

The view portion of a framework is responsible for formatting the data returned by the controller for presentation to the end user. Typically, this takes the form of some sort of template system that allows the developer to design web pages and provide for parts of the page to be generated or inserted by code. One thing to keep in mind, however, is that a web application will not always generate HTML output. It can send email in HTML or plain text, create PDF files or in a web 2.0 application, return JSON in response to an AJAX request. A robust framework will provide methods for preparing, formatting and returning various formats, not just HTML. This can save a lot of time if a developer does not have to generate all of the formatting in code or develop their own template system.

Here is an example of a Facelets template. Facelets is an open source web framework that handles the View layer for JavaServer Faces (JSF):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
	Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" 
	xmlns:h="http://java.sun.com/jsf/html">
  <body>
    <form jsfc="h:form">
      <span jsfc="h:outputText" value="Welcome, #{loggedInUser.name}" 
		disabled="#{empty loggedInUser}" />
      <input type="text" jsfc="h:inputText" 
		value="#{carBean.make}" />
      <input type="text" jsfc="h:inputText" 
		value="#{carBean.model}" />
      <input type="submit" jsfc="h:commandButton" 
		value="Add Car" action="#{carBean.addCar}" /> 
    </form>
  </body>
</html>

Bells & Whistles

The real strengths of a framework come from the many pieces of library code that provide an array of extras. Many of the existing frameworks provide an existing user authentication system and many of them are robust with granular permissions systems. In order to support authentication, most frameworks also include all the code necessary to handle session management. This makes it as easy as reading or writing from a session object for the developer.

It is also very common for frameworks to provide a library for handling web forms. In many frameworks, a generic form class or object is provided and new forms are built by subclassing. The developer defines the fields and the type of data expected and the framework does the rest. The real power of this becomes apparent when it’s time to validate a form and make sure required fields were filled in and that the data types match. Frameworks provide a default validation method but most of them also allow the developer to write custom validation routines as well.

Why Do I Need a Framework?

Frameworks provide a developer with a number of benefits. It is obvious just from the amount of code that is included in a framework that a framework provides a tremendous shortcut to a developer. The features that a framework provides creates a number of very real benefits for the developer.

Rapid Development

It does not take much to imagine how much more quickly an application can be built if the developer does not have to reinvent the database interface, template system, session code, and user authentication. Frameworks provide a means to rapidly write a web application but providing a solid starting point that already includes a great deal of functionality. This allows the developer to concentrate on the design and features of their application rather than spend time developing the foundation code.

Simplified Maintenance

Code that is developed on a foundation like a framework is often much easier to maintain. This is because the code is more modular. Core functionality is built into the framework and can be upgraded by upgrading the framework itself. The code that handles the specifics of the web application is contained in modules written by the developer. A framework also enforces certain coding conventions and styles which makes it easier to read the code later. For example, in one popular framework, the data models are built by subclassing from a generic model class. This means that all the models will be constructed in a similar way. As a result, this code is much easier to maintain.

Modular/Scalable Code

As noted earlier, code that is built on a framework tends to be modular by design. The framework itself is often built in a modular fashion to allow for a clear upgrade path as the framework evolves. Additionally, the enforcement of the model-view-controller design pattern creates an additional level of modularity. As an added benefit, this code is more scalable. It is much easier to segment database code from session code from template code. This allows different parts of the application to be distributed across an architecture and enhances scaling. This is a key benefit that the developer is gaining “for free” simply by using the framework.

More Secure Code

Code that is developed based upon a framework tends to be more secure. It is very easy to make an error in database code or code that deals with user input. Failing to check or sanitize input can often lead to security problems. A framework provides code that is mature and has been tested and vetted by numerous developers. It is less likely that a framework will contain an error that can compromise security. As a result, an application built upon one is typically more secure.

Frameworks work by providing a core library of code that defines the model-view-controller boundaries. This code provides the foundation methods of any web application such as interfacing with a database, rendering a response to a browser, and collecting form input. In addition, frameworks often provide added functionality like the ability to read and write from sessions and user authentication. Developers should consider using a framework to avoid “reinventing the wheel” which often leads to code that is hard to maintain, less secure and less scalable. Using a framework also allows a developer to rapidly develop complex applications.

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
Don't miss another post! Receive updates via email!

4 comments

  1. Techwatch says:

    rapid development is one of the huge advantages of frameworks

  2. David says:

    Merb?

    You listed Merb?

    Merb is dead – it’s been dead since 2008, when the important members of the Merb core team joined the Rails core team.

  3. Peter says:

    Controllers != business logic.

  4. bin says:

    Business should not be in controller.
    there is the Model for this purpose

Comment