Learning how to code with Frameworks


Posted over 3 years ago

When I was young and naive I wanted to code everything from scratch and rubbished any suggestion to 'buy it in'. Now I am older and slightly wiser and I am fully aware of the value of a good framework (however I still rubbish any suggestions to 'buy it in' but thats another post altogether).


What I was able to draw from this 'start from scratch' mentality of the past was the ability to really understand what was going on behind the frameworks I was to use in the future. For example how the code interacts with the databases and the issues which arise form such interaction. The downside of this mentality was, time spent doing this could have been dedicated to focusing on specific frameworks, contributing to their development, learning the good engineering practices associated with the frameworks and churning out applications faster (I'm not denouncing the value of 'do it yourself' coding specially in it's contribution to the learning process)


A few of the common advantages when using frameworks correctly are:


  • Saves coding time because code existing in the framework doesn't have to be re-written.
  • Knowledge of the framework can be transferable to other projects.
  • Frameworks generally encourage good coding practice and the use of industry standard design patterns and architectural styles.

The latter point is the one I am focusing on in this post. 2 of the most important frameworks I have developed with are ruby on rails and java spring (as well as some of the related spring projects).


Ruby on Rails One of the crucial rails concepts to grasp earily is 'convention over configuration'. Basically when working with the rails framework the developer is guided along the 'rails' of good practice via the rails conventions, from low level design patterns to high level architectural styles


An example of such guidance is in the use of the Model View Controller (MVC) architectural style that drives rails apps.


The advantages of MVC are well known, namely:


  • The modulized nature of MVC makes maintaining the code simpler, dependencies are easily identified and refactoring can be performed without having to mess with the whole system
  • Linking to the first point, in pure MVC, entire layers can replaced, you can go from a browser UI to a stand alone app without changing business logic, or switch the entire storage mechanism form XML to database.
  • Clear seperation of responsabilities between components make it easier to understand the architecture There are many more...

In rails a simple model looks like this:


class Model < ActiveRecord::Base
end

A controller class:


class ModelController < ApplicationController

  def index 
    @model = Model.find :all
  end  

  def show 
    @model = Model.find params[:id]   
  end  

  def new 
    @model = Model.new 
  end  

  def create
    @model = Model.new params[:model]
    if @model.save!  
      redirect_to @model
    else  
      render :action => "new"
    end  
  end  

  def edit 
    @model = Model.find params[:id]   
  end  

  def update 
    @model.attributes = params[:model]
    if @model.save!
      redirect_to @model  
    else
      render :action => "edit" 
    end
  end  

  def destroy 
    @model.destroy 
    redirect_to :action => 'index'
  end 
end

An extract from the view looks like this: A view example:

<div>
  &lt;% form_for @model do |f| %>
  <p>
&lt;%= f.label :body %><br>
&lt;%= f.text_field :body %>
  </p>
  <p>
    &lt;%= f.submit "Submit" %>
  </p>
  &lt;% end %>
</div>

These three class form the back bone of rails application


The Rail's base classes (above) for its models (ActiveRecord), controllers (ActiveController) and views (erb templates) provide a tight frame for the developer to implement their app in, in a MVC style. The community builds on these convention's with finer grained discussion about good practices for using the individual layers such as the exchanges about skinny controllers. I had already worked on projects which involved MVC however from rails I was able to extensivly develop my understanding of the style and worked with first hand examples of how to solve issues which may arise from using this style.


Other good practices which rails encourages through it's extensive and easy to use libraries are CRUD (Create, Read, Update, Delete) and the use of Rest.


Spring Spring uses XML to define objects which can then be constructed in the Spring container. The beauty of Spring comes in the encouragement in use of dependency injection(DI). DI is the practice of passing dependencies to an object (usually in the form of an interface) rather than defining those objects in class definition, thus not binding implementations and making refactoring, maintainig and scaling simpler.


A brief example


spring-context.xml definition, the bean spring container will read through this file and prepare for construction on demand

    &lt;!-- Big Engine object will be passed to the car object on construction but we 
             could replace BigEngine with another implementation of Engine (see below) and
             pass to car object without changing the java code -->


    &lt;!-- We could create a SmallEngine class implementing the engine interfaceand pass instead-->

Engine.java engine interface

/**
 * Defines an engine 
 */
interface Engine {

void start();

void stop();    
}

BigEngine.java implementation of Engine interface,

/**
 * A definition of an engine 
 */
class BigEngine implements Engine {

public void start() {
        System.out.println( "start...fast...." );
}

public void start() {
        System.out.println( "stop!!!" );
} 
}

Car.java

/**
 * The class which will be instantiated in main, in main the constructor attribute will not be defined
 * and can change depending on the set up of the spring-context.xml
 */
class Car {

    private Engine engine;
    // aEngine type defined in the spring-context.xml
    public Car( Engine aEngine ) {
        engine = aEngine;
    }

public void drive() {
        engine.start();
    }   
}

Main.java

class Main {
    public static void main( String[] args ) {
        // Gets a bean factory ready for constructing beans
        ClassPathXMLApplicationContext ctx = new ClassPathXMLApplicationContext(spring-context.xml);
        // constructing the car object without specifying a engine object to pass
    Car car = ctx.getBean( "car" );
        car.drive();
    }
}

The Benefits of DI aren't totally clear here and we would require a much more complicated example to really demonstrate the power. Spring really comes into it's own in enterprise solutions where new objects can be defined, constructed and utilized without recompiling the system. Going back to the previous example, if a requirement was introduced to drive a car slowly we could create a SmallEngine class and define the spring-context.xml like so (without touching existing classes):


Spring does come with it's fair share of hang-ups, It exists in the world of enterprise where complicated XML can swamp systems and dramatically increase the complexity. It requires the basic understanding of a new format and is generally more difficult to debug, however in enterprise solutions the good usually out-weigh the bad.


Conclusion I felt I needed to include code examples to illustrate the design patterns put to work in these frameworks (but the examples aren't really able to deliver how the frameworks utilize the design patterns) however the bases of the post was learning from these frameworks. Reading how a architectural style or design pattern can be used in wikipedia is far from understanding it's place in an engineers toolkit, when using these frameworks you can see first hand the implementation of such patterns and styles working to a relatively high potential.


I say relatively high because rails MVC implementation doesn't really facilitate the swapping of different layers, switching views and models. The Restful structuring could be viewed as a 'bit of a hack' because we know browsers don't support the Delete and Update HTTP functions required for a pure implementation. When drilling down into some of the spring modules I find the web service module with all the XSD, WSDL and spring-ws-context XML's messy.


Despite this, it is important to note the constructive community time that has gone into the development of these frameworks and the implementation of the design patterns and the discussion surrounding the usage. We would all gain from understanding how the patterns and styles are put to work and so when it comes to implementing them ourselves we have a high quality examples to work with.



blog comments powered by Disqus