Basic guide to setup Ruby and Ruby on Rail in Ubuntu

This beginner’s guide will set up with Ruby 1.9.3, RVM and Rails 3.2.1 and is specifically written for a development environment on Ubuntu (versions 10 through 12), but will probably work on many other operating systems, including older / newer versions of Ubuntu and Debian. YMMV.

If you’re looking for a way to set this up on a production server then I would recommend the use of the railsready script which installs all the necessary packages for Ruby 1.9.3p0 and then that version of Ruby itself, Bundler and Rails. Then it leaves it up to you to install Apache or nginx to get your application online.

If you’re not using Ubuntu then try Wayne E. Seguin’s rails_bootstrap_script which probably gets Rails 3.0.9 working for you, albeit with 1.9.1 rather than 1.9.3. But in this guide, we’re going to want to use Ruby 1.9.3 and Rails 3.2.1.

Under no circumstance should you install Ruby, Rubygems or any Ruby-related packages from apt-get. This system is out-dated and leads to major headaches. Avoid it for Ruby-related packages. We do Ruby, we know what’s best. Trust us.

Still not convinced? Read this.

This guide will go through installing the RVM (Ruby Version Manager), then a version of Ruby (1.9.3), then Rails and finally Bundler.

By the end of this guide, you will have these things installed and have some very, very easy ways to manage gem dependencies for your different applications / libraries, as well as having multiple Ruby versions installed and usable all at once.

We assume you have sudo access to your machine, and that you have an understanding of the basic concepts of Ruby, such as “What is Rubygems?” and more importantly “How do I turn this computer-thing on?”. This knowledge can be garnered by reading the first chapter of any Ruby book.

If you’re looking for a good Rails book, I wrote one called Rails 3 in Action.

Housekeeping

First of all, we’re going to run sudo apt-get update so that we have the latest sources on our box so that we don’t run into any package-related issues, such as not being able to install some packages.

Next, we’re going to install Git (a version control system) and curl which are both required to install and use RVM, and build-essential which is required to compile Ruby versions, amongst other compilable things. To install these three packages we use this command:

sudo apt-get install build-essential git-core curl

RVM

RVM is a Ruby Version Manager created by Wayne E. Seguin and is extremely helpful for installing and managing many different versions of Ruby all at once. Sometimes you could be working on a project that requires an older (1.8.7) version of Ruby but also need a new version (1.9.3) for one of your newer projects. This is a problem that RVM solves beautifully.

Another situation could be that you want to have different sets of gems on the same version of Ruby but don’t want to have to do deal with Gem Conflict Hell. RVM has gemsets for this. This is a feature you wouldn’t have if you used the packaged Ruby.

We’re going to use it to install only one version of Ruby, but we can consult the documentation if we want to install a different version of Ruby.

With git-core and curl installed we’ll be able to install RVM with this command:

curl -L get.rvm.io | bash -s stable

The beautiful part of this is that it installs Ruby to our home directory, providing a sandboxed environment just for us.

Once that’s done, we’re going to need to add a line to ~/.bashrc file (the file responsible for setting up our bash session) which will load RVM. Do this by running this command in the terminal:

echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"' >> ~/.bashrc 

Then we’ll need to reload the ~/.bashrc file which we can do with this small command:

. ~/.bashrc

The next command we run will tell us what other packages we need to install for Ruby to work:

rvm requirements
...
# For Ruby / Ruby HEAD (MRI, Rubinius, & REE), install the following:
ruby: /usr/bin/apt-get install build-essential openssl libreadline6 libreadline6-dev 
curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev
libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion

A couple of these packages we’ve already installed, such as git-core and curl. They won’t be re-installed again.

These packages will lessen the pain when we’re working with Ruby. For example, the libssl-dev package will make OpenSSL support in Ruby work, libsqlite3-0 and libsqlite3-dev are required for the sqlite3-ruby gem and the libxml2-dev and libxslt-dev packages are required for the nokogiri gem. Let’s install all these packages now using this command:

sudo apt-get install build-essential openssl libreadline6 libreadline6-dev \
curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev sqlite3 \
libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison  \
subversion

Now our Ruby lives will be as painless as possible.

Ruby

With RVM and these packages we can install Ruby 1.9.3:

rvm install 1.9.3

This command will take a couple of minutes, so grab your $DRINKOFCHOICE and go outside or something. Once it’s done, we’ll have Ruby 1.9.3 installed. To begin using it we can use this lovely command:

rvm use 1.9.3

Please note, using ‘1.9.3’ as a default allows for when ruby is updated for that version then ALL projects using 1.9.3 as their string will be updated as well. This is a side affect people might not want. The preferred method is to include the patch level to the ’–default’ parameter so that if 1.9.3 gets updated, other projects don’t automatically have that change applied to to them as well. If, say for example, for some reason some method/action gets deprecated in a patchlevel or some method signature gets changed between patchlevels, this will affect all projects defined using the ‘1.9.3’ string. This may or may not be what people want. Please be aware of this! Now, to continue on..

Are we using 1.9.3? You betcha:

ruby -v
ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-linux]

Or, even better, would be to make this the default for our user! Oooh, yes! Noting the ‘1.9.3’ side-note above, lets take note of the patchlevel, which in this case is ‘-p194’ and add that to our default selection.

rvm --default use 1.9.3-p194

Now whenever we open a new bash session for this user we’ll have Ruby available for us to use! Yay!

As an additional side-note: Users can, and should, use a gemset when possible so that they don’t pollute their ‘default’ which is what is selected when a gemset is not specified in either a project’s .rvmrc, or at the command-line. Each installed Ruby has a ‘@global’ gemset. This is used to share gems with other gemsets created under that specific Ruby, and with the ‘default’ gemset. This can be selected by running ‘rvm gemset use global’ and then installing the gems you wish to share to other gemsets including ‘default’. You can, of course simply install in each gemset but this will cause needless duplication and use up more disk-space and bandwidth.

Rails

Now that RVM and a version of Ruby is installed, we can install Rails. Because RVM is installed to our home directory, we don’t need to use that nastysudo to install things; we’ve got write-access! To install the Rails gem we’ll run this command:

gem install rails -v 3.2.3

This will install the rails gem and the other 28 gems that it and its dependencies depend on, including Bundler.

MySQL

If you’re planning on using the mysql2 gem for your application then you’ll want to install the libmysqlclient-dev package before you do that. Without it, you’ll get an error when the gem tries to compile its native extensions:

Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
	ERROR: Failed to build gem native extension.

/home/ryan/.rvm/rubies/ruby-1.9.3-p0/bin/ruby extconf.rb
checking for rb_thread_blocking_region()... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lmygcc... no
checking for mysql_query() in -lmysqlclient... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

PostgreSQL

Similar to the mysql2 gem’s error above, you’ll also get an error with the pg gem if you don’t have the libpq-dev package installed you’ll get this error:

    Building native extensions.  This could take a while...
ERROR:  Error installing pg:
	ERROR: Failed to build gem native extension.

/home/ryan/.rvm/rubies/ruby-1.9.3-p0/bin/ruby extconf.rb
checking for pg_config... no
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Fin.

And that’s it! Now you’ve got a Ruby environment you can use to write your (first?) Rails application in with such minimal effort. A good read after this would be the official guides for Ruby on Rails. Or perhaps the documentation on the RVM site which goes into using things such as gemsets and the exceptionally helpful per-project .rvmrc file. A quick way to generate an .rvmrc file is to run a command like this inside the project:

rvm use 1.9.3-p194@rails3 --rvmrc

RVM is such a powerful tool and comes in handy for day-to-day Ruby development. Use it, and not the packages from apt to live a life of development luxury.

 

Reference : http://ryanbigg.com/2010/12/ubuntu-ruby-rvm-rails-and-you/

Advertisements

Install and Configure Rhodes Application in Window x64 for cross device

If you’re running Windows, ensure that Java Development Kit is installed. The Sun JDK for Windows is available here.

Download the latest RhoStudio for Windows and run the download file to install RhoStudio.

If you use Symantec Antivirus it can warn about “Suspicious.MLApp” security risk in rubyw.exe file during installation. It is known false positive in Symantec antivirus.
Ignore this warning.
Use Motorola RhoStudio 64-bit to run RhoStudio with x64 JDK.
Use Motorola RhoStudio 32-bit to run RhoStudio with x86 JDK.

Setting path to the Java Development Kit

In RhoStudio Preferences, open RhoMobile and check that the path is set to your JDK installation.

Generating a Rhodes Application

You also can use RhoStudio to generate a RhoConnect application and source adapter. You can see an example in the RhoConnect tutorial.

In RhoStudio, select File->New->Project…

The New Project window opens. Select the RhoMobile application wizard and click the Next button.

Enter the name for your Rhodes application in Project name; in this case, “storemanager”. You may specify a specific folder for your destination where your project is stored, by default, the destination is your RhoStudio workspace folder. Uncheck the RhoElements checkbox if this is to be a strictly Rhodes application. Then press the Finish button.

After pressing the Finish button, you’ll see the Rhodes app generator script output in the output console (Rhomobile build console).

Generating a Rhodes Model

Rhodes applications support a Model-View-Controller (MVC) pattern.  To start our application, we will generate a Model. To generate a Rhodes model and create the associated Controller and View templates, right-click on the application project in the Project Explorer and select New->Rhodes model.

In the Model Information window, enter the name for your model: in this case, Product. Also enter the Model attributes as a string with no spaces and each attribute separated by a comma: in this case, name,brand,price,quantity,sku. (Whitespaces at the field name beginning and end will be trimmed and whitespaces in the middle of the field name will be replaced with an underscore character.)

Click the Finish button to create the model.

After pressing the Finish button, you’ll see the Rhodes model generator script output in the output console (Rhodes build log console).

You should now see a ‘Product’ folder below the ‘app’ folder in your storemanager application. These files constitute the Model, Views and Controller file for the Product Model we just created. The files are organized as follows:

  • product.rb –> This is the Model file which contains the Model definition. Since we are using the default PropertyBag definition, we don’t need to modify this file any further.
  • product_controller.rb –> This file contains the business logic which relates to our Model.
  • *.erb –> The .erb files are the html view template files. We’ll be modifying them in the next section.

Editing Rhodes Views

You may edit the generated ERB files to customize the HTML as you see fit. Typically you will provide links to the model index page from the home screen. In order to accomplish this, a modification needs to be made to the default view for the application, called index.erb. Below is the content for the StoreManager app’s generated top level index.erb file (app/index.erb). Open this file for editing.

Storemanager

<% if SyncEngine::logged_in > 0 %>

Sync

Logout

<% else %>
Login
<% end %>

To provide a link to the Product model’s index page and templates, replace the list item with the title ‘Add link here’ with the following:

<li>
    <a href="Product">
        <span class="title">Products</span>
    </a>
</li>

This change now means that when the index.erb view is displayed (the default view when the app starts), you will see a UI element called “Products” that will take you to the controller for the “Product” Model definition. Because no specific action is provided, the controller will default to displaying the Model’s index page, in this case the Product model’s index page. All further functionality in the app is carried out by the default scaffolding of the generated controller and view files. These generated files provide basic CRUD (Create, Read, Update, Delete) functionality for your Model.

You can edit the top level app page or any of the other view templates with any HTML you wish. We don’t attempt to teach you HTML or Ruby here, but there are many good external references for both topics.

Managing Your Build Configuration

The build.yml file for your application manages your Rhodes build time configuration. Double click on ‘build.yml’ item in your project tree to open the build.yml editor. In the editor you’ll see two tabs: Rhobuild setting for the WYSIWIG editor, and build.yml for the text editor.

Rhobuild setting WYSIWIG editor:

build.yml text editor:

You will have default values for your application name, log file (the log file will be located in your application folder after you run your application), and the path to the Rhodes gem. You can use the WYSIWIG editor to change this. For example, you might want to point to a different RHodes gem if you have more than one Rhodes gem installed.

You can add capabilities to your application, such as camera and vibrate, by pressing the Capabilities: Add button, selecting the capabilities from the popup window, and clicking the Ok button.

The selected application capabilities will appear in the Capabilities: text field in the WISIWIG editor.

Building and Running Your Application

To start the build process, create a Run Configuration: select your project in the Project Explorer, and select Run->Run Configurations… from the menu. The Run Configurations window appears.

To create a new build configuration for your application, select Rhodes Application. Then either right-click on Rhodes Application or click the New button. A new configuration appears under Rhodes Application.

Building and Running with RhoSimulator

You can run your project in RhoSimulator, a simulator type available only in RhoStudio. RhoSimulator allows you to build and run your project on the platform of your choice without having to install the SDK for that platform. Instead, RhoSImulator will mimic the platform. RhoSimulator builds and runs your application quickly, making it useful for testing and debugging.

Once you have done your application development and debugging, you will need to install the SDK to create a build for that device. Or you can upload your project to RhoHub, and use RhoHub to create the build for your device.

To run RhoSimulator for the iPhone platform, select your project from the Project Explorer (in this case, we use the storemanager project created earlier). Then select Run –> Run Configurations from the main menu. The Run Configurations window appears.

In the Run Configurations window, select RhoSimulator for the Simulator type, and select your desired platform type. For example, if you select iPhone, RhoSimulator will mimic an iPhone. The calls to the system will return as though the application was running on an actual iPhone.

Click Run to start the simulator.

In the storemanager example, we can add a couple of products. Click the Products link, then click New, enter the product attributes, and click Create.

Using the Web Inspector

The RhoSimulator also brings up a Webkit Inspector window, allowing you to inspect the web interface for your application.

For example, you can see the web code for the listview. Here is the listview of the products for the storemanager example. You can see the link for the iPhone URL, and you could change the border color and thickness for the iPhone product (changing from 1px to 3px and solid #CCC to #111 would give the iPhone link a thicker, darker border).

Using the Debugger

You can use the RhoStudio debugger to debug the Ruby code in your RHodes or Rhoconnect application.

Debugging a Rhodes Application

To run the RhoSimulator debugger for the iPhone platform, select your Rhodes project from the Project Explorer (in this case, we use the storemanager project created earlier). Then select Run –> Debug Configurations from the main menu. The Debug Configurations window appears.

Click Debug to start the debugger.

You will again get a RhoSimulator showing your device, and the Web Inspector window. And you get a Debug view in your workspace.

To debug your Ruby code in your Rhodes application, click the RhoStudio tab in your workspace, then open the Ruby file in your Rhodes application that you wish to debug.

Now click the Debug tab. You will see the Ruby file opened in the debugger.

Debugging a RhoConnect Application

To run the debugger for RhoConnect, select your RhoConnect project from the Project Explorer. Then select Run –> Debug Configurations from the main menu. The Debug Configurations window appears.

Click Debug to start the debugger.

You will see your RhoConnect project in the debugger; there will be a console window with redis server information messages. (You will not get a RhoSimulator or a Web Inspector, as you do with the Rhodes debugger.)

To debug your Ruby code in your RhoConnect application, you do the same as for a Rhodes application: click the RhoStudio tab in your workspace, then open the Ruby file in your RhoConnect project that you wish to debug.

Setting a Breakpoint

You can perform operations such as setting a breakpoint: double-click in the left margin at the line of code where you want the breakpoint.

For example, in the storemanager code, there is a rendering section in product_controller.rb.

# GET /Product
def index
  @products = Product.find(:all)
  render :back => '/app'
end

You can set a breakpoint on the line render :back => '/app', then you can go to the RhoSimulator and click on Product. The simulator will stop at the point of rendering.

If you set a breakpoint on a function definition string (the first line of a function definition), as in the following line of Ruby code, that breakpoint will always be disabled. You should not set breakpoints there.
def some_method(value='default', arr=[])

Inspecting the Variables

You can also inspect the variables. When you click “Products” In the debugger simulator, and you have a breakpoint as set earlier in the product_controller.rb on the rendering line, the application will pause just before the rendering of the product listing page. You can then inspect the variables in the variable window. The storemanager example shows that at this point int he app, the local database has been read, showing that a couple of products have been created (an iPhone and an iPhone4S).

Debugger Support for Extensions

The RhoStudio debugger supports extensions, but only pure Ruby extensions or the Ruby part of a native extension.

Debugging Ruby Framework Code

The debugger supports debugging Ruby framework code. With an older project, you may need to recreate the project in RhoStudio in order to enable the debugger. A good way to do this is as follows.

  1. Delete the project in the Project Explorer view without deleting the project content.
  2. Create a new project by creating from existing sources in the RhoMobile application wizard.
  3. Use your old project content as the existing source.

Importing a Rhodes Project from a non-RhoStudio Source

You can have a Rhodes project that you wish to import into RhoStudio. For example, you might have created a project using RhoHub and you have a local repository of that project on your computer). Or you might want to import the sample projects that came with the RhoStudio installer. The import process is similar to importing external projects with standard Eclipse.

Select File –> New –> Project…

From the New Project window, select Rhomobile –> Rhoconnect application or Rhomobile –> Rhodes application. THen click the Next button.

From the Rhodes (or Rhoconnect) application generator wizard window, click the “Create application from existing sources” checkbox.

Click the Browse button, then navigate to and select the folder containing your project. The Project name will change to the name of your project folder.

Click the Finish button. Your project will appear in the Project Explorer.

Creating a Device Build in RhoStudio

Once you have developed your application using the RhoSimulator and debugger, you will need to create a device build of your application. To do this with RhoStudio, you can do this by installing SDKs.

To create a device build with RhoStudio, you need to do the following:

  • Install the SDK for your application’s platform.
  • Set RhoStudio Preferences to that platform’s SDK.
  • In Run Configurations, set to that device, then do the device build and run.
You can do the device build with RhoHub if you wish to avoid installing the SDKs on your computer. To do your device build on RhoHub, upload your application into RhoHub, then use RhoHub to create the device build. Instructions for using RhoHub are in the Rhohub tutorial.

Installing the SDK

On Macintosh computers, once you have installed Xcode, RhoStudio will know the location of the iOS SDK. You do not set any locations.

On other platforms, such as Android, you need to install the SDK, and then set RhoStudio Preferences for that platform’s SDK. For example, on an Android device, you must download and install:

Set RhoStudio SDK Preferences

Once you have the SDK for your platform installed, set RhoStudio Preferences for that SDK. For example, to do Android device builds:

  1. In the Preferences window, open the Rhomobile item and select Android.
  2. Click the Browse button and navigate to the locations where you installed your Android SDK and NDK.

Set Run Configurations to the Device Build and Run

To start the device build process, create a Run Configuration: select your project in the Project Explorer, and select Run->Run Configurations… from the menu. The Run Configurations window appears. Set Run Configurations as follows:

  • Set the Platform to Android.
  • Set the Simulator type to either device to run on the device, or simulator to run on the simulator provided with the Android SDK.
  • If you set the Simulator type to simulator, set the Platform version number and set the AVD name for Android.

Press the Run button to build and run your application. The build output will appear in the Rhodes build output console. The application log will be available in the Rhodes application output console, and will be written into your application folder.

For complete instructions on setting up the SDKs in RhoStudio for each platform, refer to the Build instructions for Rhodes.

Editing the SDK Locations in rhobuild.yml

Use RhoStudio preferences to edit the rhobuild.yml file, which manages the location(s) of the platform SDKs/JDKs that are used to build your Rhodes application. The rhobuild.yml file is located in the Rhodes gem folder (or, if you copied Rhodes from git, in the Rhodes source code folder).

Using Intellisense for Autocompletion

IntelliSense is Microsoft’s implementation of autocompletion, best known for its use in the Microsoft Visual Studio integrated development environment. In addition to completing the symbol names the programmer is typing, IntelliSense serves as documentation and disambiguation for variable names, functions and methods using reflection.

The RhoStudio DLTK implementation supports aspects of Intellisense, such as Ruby keyword completion and block argument name completion. You can use Intellisense in RhoStudio to autocomplete your Ruby code by setting the cursor at a location in your code and pressing Ctrl+Space.

For example, to complete a Ruby keyword beginning with “re”, perform these steps.

  1. Enter “re”.
  2. Press Ctrl+Space. The completion list includes “rescue” and “return”.

Checking Progress and Canceling an Operation

You can check the progress of an operation in RhoStudio, and cancel it if you wish. Open the Progress view to see the progress bar on the left, and click the red square on the right to cancel the operation.

The following RhoStudio operations can have their progress checked and be canceled from the Progress view.

  • Main menu: RhoMobile –> Production build
  • Main menu: Project –> Clean…
  • RhoMobile Application in Project Explorer: Run Configurations, RhoMobile Application
  • RhoMobile Application in Project Explorer: Run Configurations, RhoMobile Application Test
  • RhoConnect Application in Project Explorer: Run Configurations, RhoConnect Application

You can also check progress and perform a cancel for the following operations on existing applications.

  • Create a new project, and then select RhoMobile->RhoMobile application from the New Project window.
  • Create a new project, and then select RhoMobile->RhoConnect application from the New Project window.
  • Select a RhoMobile application in the Project Explorer, and create a New->RhoMobile model.
  • Select a RhoMobile application in the Project Explorer, and create a New->RhoMobile extension.
  • Select a RhoConnect application in the Project Explorer, and create a New->RhoConnect source adapter.

Creating a Production Build in RhoStudio

To create a production build for your application, perform these steps.

  1. Select your application in the Project Explorer.
  2. Select RhoMobile->Production Build from the main menu.
  3. From the Select platform pop-up box, select the platform to which you wish to build and click “Ok”.

Reference : http://docs.rhomobile.com/rhostudio.tutorial#managing-your-build-configuration

Inversion of Control Containers and the Dependency Injection pattern

I really like this article as so far I never understand about all of these terms.
Really thanks to Martin Fowler for his good article.

————————————————————————————————————————————————————–

In the Java community there’s been a rush of lightweight containers that help to assemble components from different projects into a cohesive application. Underlying these containers is a common pattern to how they perform the wiring, a concept they refer under the very generic name of “Inversion of Control“. In this article I dig into how this pattern works, under the more specific name of “Dependency Injection“, and contrast it with the Service Locator alternative. The choice between them is less important than the principle of separating configuration from use.

One of the entertaining things about the enterprise Java world is the huge amount of activity in building alternatives to the mainstream J2EE technologies, much of it happening in open source. A lot of this is a reaction to the heavyweight complexity in the mainstream J2EE world, but much of it is also exploring alternatives and coming up with creative ideas. A common issue to deal with is how to wire together different elements: how do you fit together this web controller architecture with that database interface backing when they were built by different teams with little knowledge of each other.A number of frameworks have taken a stab at this problem, and several are branching out to provide a general capability to assemble components from different layers. These are often referred to as lightweight containers, examples include PicoContainer, and Spring.

Underlying these containers are a number of interesting design principles, things that go beyond both these specific containers and indeed the Java platform. Here I want to start exploring some of these principles. The examples I use are in Java, but like most of my writing the principles are equally applicable to other OO environments, particularly .NET.


Components and Services

The topic of wiring elements together drags me almost immediately into the knotty terminology problems that surround the terms service and component. You find long and contradictory articles on the definition of these things with ease. For my purposes here are my current uses of these overloaded terms.

I use component to mean a glob of software that’s intended to be used, without change, by an application that is out of the control of the writers of the component. By ‘without change’ I mean that the using application doesn’t change the source code of the components, although they may alter the component’s behavior by extending it in ways allowed by the component writers.

A service is similar to a component in that it’s used by foreign applications. The main difference is that I expect a component to be used locally (think jar file, assembly, dll, or a source import). A service will be used remotely through some remote interface, either synchronous or asynchronous (eg web service, messaging system, RPC, or socket.)

I mostly use service in this article, but much of the same logic can be applied to local components too. Indeed often you need some kind of local component framework to easily access a remote service. But writing “component or service” is tiring to read and write, and services are much more fashionable at the moment.

A Naive Example

To help make all of this more concrete I’ll use a running example to talk about all of this. Like all of my examples it’s one of those super-simple examples; small enough to be unreal, but hopefully enough for you to visualize what’s going on without falling into the bog of a real example.

In this example I’m writing a component that provides a list of movies directed by a particular director. This stunningly useful function is implemented by a single method.

class MovieLister...
    public Movie[] moviesDirectedBy(String arg) {
        List allMovies = finder.findAll();
        for (Iterator it = allMovies.iterator(); it.hasNext();) {
            Movie movie = (Movie) it.next();
            if (!movie.getDirector().equals(arg)) it.remove();
        }
        return (Movie[]) allMovies.toArray(new Movie[allMovies.size()]);
    }

The implementation of this function is naive in the extreme, it asks a finder object (which we’ll get to in a moment) to return every film it knows about. Then it just hunts through this list to return those directed by a particular director. This particular piece of naivety I’m not going to fix, since it’s just the scaffolding for the real point of this article.

The real point of this article is this finder object, or particularly how we connect the lister object with a particular finder object. The reason why this is interesting is that I want my wonderful moviesDirectedBy method to be completely independent of how all the movies are being stored. So all the method does is refer to a finder, and all that finder does is know how to respond to the findAll method. I can bring this out by defining an interface for the finder.

public interface MovieFinder {
    List findAll();
}

Now all of this is very well decoupled, but at some point I have to come up with a concrete class to actually come up with the movies. In this case I put the code for this in the constructor of my lister class.

class MovieLister...
  private MovieFinder finder;
  public MovieLister() {
    finder = new ColonDelimitedMovieFinder("movies1.txt");
  }

The name of the implementation class comes from the fact that I’m getting my list from a colon delimited text file. I’ll spare you the details, after all the point is just that there’s some implementation.

Now if I’m using this class for just myself, this is all fine and dandy. But what happens when my friends are overwhelmed by a desire for this wonderful functionality and would like a copy of my program? If they also store their movie listings in a colon delimited text file called “movies1.txt” then everything is wonderful. If they have a different name for their movies file, then it’s easy to put the name of the file in a properties file. But what if they have a completely different form of storing their movie listing: a SQL database, an XML file, a web service, or just another format of text file? In this case we need a different class to grab that data. Now because I’ve defined a MovieFinder interface, this won’t alter mymoviesDirectedBy method. But I still need to have some way to get an instance of the right finder implementation into place.

Figure 1

Figure 1: The dependencies using a simple creation in the lister class

Figure 1 shows the dependencies for this situation. The MovieLister class is dependent on both the MovieFinder interface and upon the implementation. We would prefer it if it were only dependent on the interface, but then how do we make an instance to work with?

In my book P of EAA, we described this situation as a Plugin. The implementation class for the finder isn’t linked into the program at compile time, since I don’t know what my friends are going to use. Instead we want my lister to work with any implementation, and for that implementation to be plugged in at some later point, out of my hands. The problem is how can I make that link so that my lister class is ignorant of the implementation class, but can still talk to an instance to do its work.

Expanding this into a real system, we might have dozens of such services and components. In each case we can abstract our use of these components by talking to them through an interface (and using an adapter if the component isn’t designed with an interface in mind). But if we wish to deploy this system in different ways, we need to use plugins to handle the interaction with these services so we can use different implementations in different deployments.

So the core problem is how do we assemble these plugins into an application? This is one of the main problems that this new breed of lightweight containers face, and universally they all do it using Inversion of Control.


Inversion of Control

When these containers talk about how they are so useful because they implement “Inversion of Control” I end up very puzzled. Inversion of control is a common characteristic of frameworks, so saying that these lightweight containers are special because they use inversion of control is like saying my car is special because it has wheels.

The question, is what aspect of control are they inverting? When I first ran into inversion of control, it was in the main control of a user interface. Early user interfaces were controlled by the application program. You would have a sequence of commands like “Enter name”, “enter address”; your program would drive the prompts and pick up a response to each one. With graphical (or even screen based) UIs the UI framework would contain this main loop and your program instead provided event handlers for the various fields on the screen. The main control of the program was inverted, moved away from you to the framework.

For this new breed of containers the inversion is about how they lookup a plugin implementation. In my naive example the lister looked up the finder implementation by directly instantiating it. This stops the finder from being a plugin. The approach that these containers use is to ensure that any user of a plugin follows some convention that allows a separate assembler module to inject the implementation into the lister.

As a result I think we need a more specific name for this pattern. Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection.

I’m going to start by talking about the various forms of dependency injection, but I’ll point out now that that’s not the only way of removing the dependency from the application class to the plugin implementation. The other pattern you can use to do this is Service Locator, and I’ll discuss that after I’m done with explaining Dependency Injection.


Forms of Dependency Injection

The basic idea of the Dependency Injection is to have a separate object, an assembler, that populates a field in the lister class with an appropriate implementation for the finder interface, resulting in a dependency diagram along the lines of Figure 2

Figure 2

Figure 2: The dependencies for a Dependency Injector

There are three main styles of dependency injection. The names I’m using for them are Constructor Injection, Setter Injection, and Interface Injection. If you read about this stuff in the current discussions about Inversion of Control you’ll hear these referred to as type 1 IoC (interface injection), type 2 IoC (setter injection) and type 3 IoC (constructor injection). I find numeric names rather hard to remember, which is why I’ve used the names I have here.

Constructor Injection with PicoContainer

I’ll start with showing how this injection is done using a lightweight container calledPicoContainer. I’m starting here primarily because several of my colleagues at ThoughtWorks are very active in the development of PicoContainer (yes, it’s a sort of corporate nepotism.)

PicoContainer uses a constructor to decide how to inject a finder implementation into the lister class. For this to work, the movie lister class needs to declare a constructor that includes everything it needs injected.

class MovieLister...
    public MovieLister(MovieFinder finder) {
        this.finder = finder;       
    }

The finder itself will also be managed by the pico container, and as such will have the filename of the text file injected into it by the container.

class ColonMovieFinder...
    public ColonMovieFinder(String filename) {
        this.filename = filename;
    }

The pico container then needs to be told which implementation class to associate with each interface, and which string to inject into the finder.

    private MutablePicoContainer configureContainer() {
        MutablePicoContainer pico = new DefaultPicoContainer();
        Parameter[] finderParams =  {new ConstantParameter("movies1.txt")};
        pico.registerComponentImplementation(MovieFinder.class, ColonMovieFinder.class, finderParams);
        pico.registerComponentImplementation(MovieLister.class);
        return pico;
    }

This configuration code is typically set up in a different class. For our example, each friend who uses my lister might write the appropriate configuration code in some setup class of their own. Of course it’s common to hold this kind of configuration information in separate config files. You can write a class to read a config file and set up the container appropriately. Although PicoContainer doesn’t contain this functionality itself, there is a closely related project called NanoContainer that provides the appropriate wrappers to allow you to have XML configuration files. Such a nano container will parse the XML and then configure an underlying pico container. The philosophy of the project is to separate the config file format from the underlying mechanism.

To use the container you write code something like this.

    public void testWithPico() {
        MutablePicoContainer pico = configureContainer();
        MovieLister lister = (MovieLister) pico.getComponentInstance(MovieLister.class);
        Movie[] movies = lister.moviesDirectedBy("Sergio Leone");
        assertEquals("Once Upon a Time in the West", movies[0].getTitle());
    }

Although in this example I’ve used constructor injection, PicoContainer also supports setter injection, although its developers do prefer constructor injection.

Setter Injection with Spring

The Spring framework is a wide ranging framework for enterprise Java development. It includes abstraction layers for transactions, persistence frameworks, web application development and JDBC. Like PicoContainer it supports both constructor and setter injection, but its developers tend to prefer setter injection – which makes it an appropriate choice for this example.

To get my movie lister to accept the injection I define a setting method for that service

class MovieLister...
    private MovieFinder finder;
  public void setFinder(MovieFinder finder) {
    this.finder = finder;
  }

Similarly I define a setter for the filename.

class ColonMovieFinder...
    public void setFilename(String filename) {
        this.filename = filename;
    }

The third step is to set up the configuration for the files. Spring supports configuration through XML files and also through code, but XML is the expected way to do it.

    <beans>
        <bean id="MovieLister">
            <property name="finder">
                <ref local="MovieFinder"/>
            </property>
        </bean>
        <bean id="MovieFinder">
            <property name="filename">
                <value>movies1.txt</value>
            </property>
        </bean>
    </beans>

The test then looks like this.

    public void testWithSpring() throws Exception {
        ApplicationContext ctx = new FileSystemXmlApplicationContext("spring.xml");
        MovieLister lister = (MovieLister) ctx.getBean("MovieLister");
        Movie[] movies = lister.moviesDirectedBy("Sergio Leone");
        assertEquals("Once Upon a Time in the West", movies[0].getTitle());
    }

Interface Injection

The third injection technique is to define and use interfaces for the injection. Avalon is an example of a framework that uses this technique in places. I’ll talk a bit more about that later, but in this case I’m going to use it with some simple sample code.

With this technique I begin by defining an interface that I’ll use to perform the injection through. Here’s the interface for injecting a movie finder into an object.

public interface InjectFinder {
    void injectFinder(MovieFinder finder);
}

This interface would be defined by whoever provides the MovieFinder interface. It needs to be implemented by any class that wants to use a finder, such as the lister.

class MovieLister implements InjectFinder...
    public void injectFinder(MovieFinder finder) {
        this.finder = finder;
    }

I use a similar approach to inject the filename into the finder implementation.

public interface InjectFinderFilename {
    void injectFilename (String filename);
}

class ColonMovieFinder implements MovieFinder, InjectFinderFilename......
    public void injectFilename(String filename) {
        this.filename = filename;
    }

Then, as usual, I need some configuration code to wire up the implementations. For simplicity’s sake I’ll do it in code.

class Tester...
    private Container container;

     private void configureContainer() {
       container = new Container();
       registerComponents();
       registerInjectors();
       container.start();
    }

This configuration has two stages, registering components through lookup keys is pretty similar to the other examples.

class Tester...
  private void registerComponents() {
    container.registerComponent("MovieLister", MovieLister.class);
    container.registerComponent("MovieFinder", ColonMovieFinder.class);
  }

A new step is to register the injectors that will inject the dependent components. Each injection interface needs some code to inject the dependent object. Here I do this by registering injector objects with the container. Each injector object implements the injector interface.

class Tester...
  private void registerInjectors() {
    container.registerInjector(InjectFinder.class, container.lookup("MovieFinder"));
    container.registerInjector(InjectFinderFilename.class, new FinderFilenameInjector());
  }

public interface Injector {
  public void inject(Object target);

}

When the dependent is a class written for this container, it makes sense for the component to implement the injector interface itself, as I do here with the movie finder. For generic classes, such as the string, I use an inner class within the configuration code.

class ColonMovieFinder implements Injector......
  public void inject(Object target) {
    ((InjectFinder) target).injectFinder(this);        
  }

class Tester...
  public static class FinderFilenameInjector implements Injector {
    public void inject(Object target) {
      ((InjectFinderFilename)target).injectFilename("movies1.txt");      
    }
    }

The tests then use the container.

class IfaceTester...
    public void testIface() {
      configureContainer();
      MovieLister lister = (MovieLister)container.lookup("MovieLister");
      Movie[] movies = lister.moviesDirectedBy("Sergio Leone");
      assertEquals("Once Upon a Time in the West", movies[0].getTitle());
    }

The container uses the declared injection interfaces to figure out the dependencies and the injectors to inject the correct dependents. (The specific container implementation I did here isn’t important to the technique, and I won’t show it because you’d only laugh.)


Using a Service Locator

The key benefit of a Dependency Injector is that it removes the dependency that theMovieLister class has on the concrete MovieFinder implementation. This allows me to give listers to friends and for them to plug in a suitable implementation for their own environment. Injection isn’t the only way to break this dependency, another is to use aservice locator.

The basic idea behind a service locator is to have an object that knows how to get hold of all of the services that an application might need. So a service locator for this application would have a method that returns a movie finder when one is needed. Of course this just shifts the burden a tad, we still have to get the locator into the lister, resulting in the dependencies of Figure 3

Figure 3

Figure 3: The dependencies for a Service Locator

In this case I’ll use the ServiceLocator as a singleton Registry. The lister can then use that to get the finder when it’s instantiated.

class MovieLister...
    MovieFinder finder = ServiceLocator.movieFinder();

class ServiceLocator...
    public static MovieFinder movieFinder() {
        return soleInstance.movieFinder;
    }
    private static ServiceLocator soleInstance;
    private MovieFinder movieFinder;

As with the injection approach, we have to configure the service locator. Here I’m doing it in code, but it’s not hard to use a mechanism that would read the appropriate data from a configuration file.

class Tester...
    private void configure() {
        ServiceLocator.load(new ServiceLocator(new ColonMovieFinder("movies1.txt")));
    }

class ServiceLocator...
    public static void load(ServiceLocator arg) {
        soleInstance = arg;
    }

    public ServiceLocator(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

Here’s the test code.

class Tester...
    public void testSimple() {
        configure();
        MovieLister lister = new MovieLister();
        Movie[] movies = lister.moviesDirectedBy("Sergio Leone");
        assertEquals("Once Upon a Time in the West", movies[0].getTitle());
    }

I’ve often heard the complaint that these kinds of service locators are a bad thing because they aren’t testable because you can’t substitute implementations for them. Certainly you can design them badly to get into this kind of trouble, but you don’t have to. In this case the service locator instance is just a simple data holder. I can easily create the locator with test implementations of my services.

For a more sophisticated locator I can subclass service locator and pass that subclass into the registry’s class variable. I can change the static methods to call a method on the instance rather accessing instance variables directly. I can provide thread specific locators by using thread specific storage. All of this can be done without changing clients of service locator.

A way to think of this is that service locator is a registry not a singleton. A singleton provides a simple way of implementing a registry, but that implementation decision is easily changed.

Using a Segregated Interface for the Locator

One of the issues with the simple approach above, is that the MovieLister is dependent on the full service locator class, even though it only uses one service. We can reduce this by using a segregated interface. That way, instead of using the full service locator interface, the lister can declare just the bit of interface it needs.

In this situation the provider of the lister would also provide a locator interface which it needs to get hold of the finder.

public interface MovieFinderLocator {
    public MovieFinder movieFinder();

The locator then needs to implement this interface to provide access to a finder.

    MovieFinderLocator locator = ServiceLocator.locator();
    MovieFinder finder = locator.movieFinder();

   public static ServiceLocator locator() {
        return soleInstance;
    }
    public MovieFinder movieFinder() {
        return movieFinder;
    }
    private static ServiceLocator soleInstance;
    private MovieFinder movieFinder;

You’ll notice that since we want to use an interface, we can’t just access the services through static methods any more. We have to use the class to get a locator instance and then use that to get what we need.

A Dynamic Service Locator

The above example was static, in that the service locator class has methods for each of the services that you need. This isn’t the only way of doing it, you can also make a dynamic service locator that allows you to stash any service you need into it and make your choices at runtime.

In this case, the service locator uses a map instead of fields for each of the services, and provides generic methods to get and load services.

class ServiceLocator...
    private static ServiceLocator soleInstance;
    public static void load(ServiceLocator arg) {
        soleInstance = arg;
    }
    private Map services = new HashMap();
    public static Object getService(String key){
        return soleInstance.services.get(key);
    }
    public void loadService (String key, Object service) {
        services.put(key, service);
    }

Configuring involves loading a service with an appropriate key.

class Tester...
    private void configure() {
        ServiceLocator locator = new ServiceLocator();
        locator.loadService("MovieFinder", new ColonMovieFinder("movies1.txt"));
        ServiceLocator.load(locator);
    }

I use the service by using the same key string.

class MovieLister...
    MovieFinder finder = (MovieFinder) ServiceLocator.getService("MovieFinder");

On the whole I dislike this approach. Although it’s certainly flexible, it’s not very explicit. The only way I can find out how to reach a service is through textual keys. I prefer explicit methods because it’s easier to find where they are by looking at the interface definitions.

Using both a locator and injection with Avalon

Dependency injection and a service locator aren’t necessarily mutually exclusive concepts. A good example of using both together is the Avalon framework. Avalon uses a service locator, but uses injection to tell components where to find the locator.

Berin Loritsch sent me this simple version of my running example using Avalon.

public class MyMovieLister implements MovieLister, Serviceable {
    private MovieFinder finder;    public void service( ServiceManager manager ) throws ServiceException {
        finder = (MovieFinder)manager.lookup("finder");
    }

The service method is an example of interface injection, allowing the container to inject a service manager into MyMovieLister. The service manager is an example of a service locator. In this example the lister doesn’t store the manager in a field, instead it immediately uses it to lookup the finder, which it does store.


Deciding which option to use

So far I’ve concentrated on explaining how I see these patterns and their variations. Now I can start talking about their pros and cons to help figure out which ones to use and when.

Service Locator vs Dependency Injection

The fundamental choice is between Service Locator and Dependency Injection. The first point is that both implementations provide the fundamental decoupling that’s missing in the naive example – in both cases application code is independent of the concrete implementation of the service interface. The important difference between the two patterns is about how that implementation is provided to the application class. With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class – hence the inversion of control.

Inversion of control is a common feature of frameworks, but it’s something that comes at a price. It tends to be hard to understand and leads to problems when you are trying to debug. So on the whole I prefer to avoid it unless I need it. This isn’t to say it’s a bad thing, just that I think it needs to justify itself over the more straightforward alternative.

The key difference is that with a Service Locator every user of a service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the locator. So the decision between locator and injector depends on whether that dependency is a problem.

Using dependency injection can help make it easier to see what the component dependencies are. With dependency injector you can just look at the injection mechanism, such as the constructor, and see the dependencies. With the service locator you have to search the source code for calls to the locator. Modern IDEs with a find references feature make this easier, but it’s still not as easy as looking at the constructor or setting methods.

A lot of this depends on the nature of the user of the service. If you are building an application with various classes that use a service, then a dependency from the application classes to the locator isn’t a big deal. In my example of giving a Movie Lister to my friends, then using a service locator works quite well. All they need to do is to configure the locator to hook in the right service implementations, either through some configuration code or through a configuration file. In this kind of scenario I don’t see the injector’s inversion as providing anything compelling.

The difference comes if the lister is a component that I’m providing to an application that other people are writing. In this case I don’t know much about the APIs of the service locators that my customers are going to use. Each customer might have their own incompatible service locators. I can get around some of this by using the segregated interface. Each customer can write an adapter that matches my interface to their locator, but in any case I still need to see the first locator to lookup my specific interface. And once the adapter appears then the simplicity of the direct connection to a locator is beginning to slip.

Since with an injector you don’t have a dependency from a component to the injector, the component cannot obtain further services from the injector once it’s been configured.

A common reason people give for preferring dependency injection is that it makes testing easier. The point here is that to do testing, you need to easily replace real service implementations with stubs or mocks. However there is really no difference here between dependency injection and service locator: both are very amenable to stubbing. I suspect this observation comes from projects where people don’t make the effort to ensure that their service locator can be easily substituted. This is where continual testing helps, if you can’t easily stub services for testing, then this implies a serious problem with your design.

Of course the testing problem is exacerbated by component environments that are very intrusive, such as Java’s EJB framework. My view is that these kinds of frameworks should minimize their impact upon application code, and particularly should not do things that slow down the edit-execute cycle. Using plugins to substitute heavyweight components does a lot to help this process, which is vital for practices such as Test Driven Development.

So the primary issue is for people who are writing code that expects to be used in applications outside of the control of the writer. In these cases even a minimal assumption about a Service Locator is a problem.

Constructor versus Setter Injection

For service combination, you always have to have some convention in order to wire things together. The advantage of injection is primarily that it requires very simple conventions – at least for the constructor and setter injections. You don’t have to do anything odd in your component and it’s fairly straightforward for an injector to get everything configured.

Interface injection is more invasive since you have to write a lot of interfaces to get things all sorted out. For a small set of interfaces required by the container, such as in Avalon’s approach, this isn’t too bad. But it’s a lot of work for assembling components and dependencies, which is why the current crop of lightweight containers go with setter and constructor injection.

The choice between setter and constructor injection is interesting as it mirrors a more general issue with object-oriented programming – should you fill fields in a constructor or with setters.

My long running default with objects is as much as possible, to create valid objects at construction time. This advice goes back to Kent Beck’s Smalltalk Best Practice Patterns: Constructor Method and Constructor Parameter Method. Constructors with parameters give you a clear statement of what it means to create a valid object in an obvious place. If there’s more than one way to do it, create multiple constructors that show the different combinations.

Another advantage with constructor initialization is that it allows you to clearly hide any fields that are immutable by simply not providing a setter. I think this is important – if something shouldn’t change then the lack of a setter communicates this very well. If you use setters for initialization, then this can become a pain. (Indeed in these situations I prefer to avoid the usual setting convention, I’d prefer a method like initFoo, to stress that it’s something you should only do at birth.)

But with any situation there are exceptions. If you have a lot of constructor parameters things can look messy, particularly in languages without keyword parameters. It’s true that a long constructor is often a sign of an over-busy object that should be split, but there are cases when that’s what you need.

If you have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on the number and type of parameters. This is when Factory Methods come into play, these can use a combination of private constructors and setters to implement their work. The problem with classic Factory Methods for components assembly is that they are usually seen as static methods, and you can’t have those on interfaces. You can make a factory class, but then that just becomes another service instance. A factory service is often a good tactic, but you still have to instantiate the factory using one of the techniques here.

Constructors also suffer if you have simple parameters such as strings. With setter injection you can give each setter a name to indicate what the string is supposed to do. With constructors you are just relying on the position, which is harder to follow.

If you have multiple constructors and inheritance, then things can get particularly awkward. In order to initialize everything you have to provide constructors to forward to each superclass constructor, while also adding you own arguments. This can lead to an even bigger explosion of constructors.

Despite the disadvantages my preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I’ve outlined above start to become a problem.

This issue has led to a lot of debate between the various teams who provide dependency injectors as part of their frameworks. However it seems that most people who build these frameworks have realized that it’s important to support both mechanisms, even if there’s a preference for one of them.

Code or configuration files

A separate but often conflated issue is whether to use configuration files or code on an API to wire up services. For most applications that are likely to be deployed in many places, a separate configuration file usually makes most sense. Almost all the time this will be an XML file, and this makes sense. However there are cases where it’s easier to use program code to do the assembly. One case is where you have a simple application that’s not got a lot of deployment variation. In this case a bit of code can be clearer than a separate XML file.

A contrasting case is where the assembly is quite complex, involving conditional steps. Once you start getting close to programming language then XML starts breaking down and it’s better to use a real language that has all the syntax to write a clear program. You then write a builder class that does the assembly. If you have distinct builder scenarios you can provide several builder classes and use a simple configuration file to select between them.

I often think that people are over-eager to define configuration files. Often a programming language makes a straightforward and powerful configuration mechanism. Modern languages can easily compile small assemblers that can be used to assemble plugins for larger systems. If compilation is a pain, then there are scripting languages that can work well also.

It’s often said that configuration files shouldn’t use a programing language because they need to be edited by non-programmers. But how often is this the case? Do people really expect non-programmers to alter the transaction isolation levels of a complex server-side application? Non-language configuration files work well only to the extent they are simple. If they become complex then it’s time to think about using a proper programming language.

One thing we’re seeing in the Java world at the moment is a cacophony of configuration files, where every component has its own configuration files which are different to everyone else’s. If you use a dozen of these components, you can easily end up with a dozen configuration files to keep in sync.

My advice here is to always provide a way to do all configuration easily with a programmatic interface, and then treat a separate configuration file as an optional feature. You can easily build configuration file handling to use the programmatic interface. If you are writing a component you then leave it up to your user whether to use the programmatic interface, your configuration file format, or to write their own custom configuration file format and tie it into the programmatic interface

Separating Configuration from Use

The important issue in all of this is to ensure that the configuration of services is separated from their use. Indeed this is a fundamental design principle that sits with the separation of interfaces from implementation. It’s something we see within an object-oriented program when conditional logic decides which class to instantiate, and then future evaluations of that conditional are done through polymorphism rather than through duplicated conditional code.

If this separation is useful within a single code base, it’s especially vital when you’re using foreign elements such as components and services. The first question is whether you wish to defer the choice of implementation class to particular deployments. If so you need to use some implementation of plugin. Once you are using plugins then it’s essential that the assembly of the plugins is done separately from the rest of the application so that you can substitute different configurations easily for different deployments. How you achieve this is secondary. This configuration mechanism can either configure a service locator, or use injection to configure objects directly.


Some further issues

In this article, I’ve concentrated on the basic issues of service configuration using Dependency Injection and Service Locator. There are some more topics that play into this which also deserve attention, but I haven’t had time yet to dig into. In particular there is the issue of life-cycle behavior. Some components have distinct life-cycle events: stop and starts for instance. Another issue is the growing interest in using aspect oriented ideas with these containers. Although I haven’t considered this material in the article at the moment, I do hope to write more about this either by extending this article or by writing another.

You can find out a lot more about these ideas by looking at the web sites devoted to the lightweight containers. Surfing from the picocontainer and spring web sites will lead to you into much more discussion of these issues and a start on some of the further issues.


Concluding Thoughts

The current rush of lightweight containers all have a common underlying pattern to how they do service assembly – the dependency injector pattern. Dependency Injection is a useful alternative to Service Locator. When building application classes the two are roughly equivalent, but I think Service Locator has a slight edge due to its more straightforward behavior. However if you are building classes to be used in multiple applications then Dependency Injection is a better choice.

If you use Dependency Injection there are a number of styles to choose between. I would suggest you follow constructor injection unless you run into one of the specific problems with that approach, in which case switch to setter injection. If you are choosing to build or obtain a container, look for one that supports both constructor and setter injection.

The choice between Service Locator and Dependency Injection is less important than the principle of separating service configuration from the use of services within an application.

Reference : http://martinfowler.com/articles/injection.html

PhoneGap for Android Native App

PhoneGap is an open source framework for quickly building cross-platform mobile apps using HTML5, Javascript and CSS.

Building applications for each device–iPhone, Android, Windows Mobile and more–requires different frameworks and languages. PhoneGap solves this by using standards-based web technologies to bridge web applications and mobile devices. Since PhoneGap apps are standards compliant, they’re future-proofed to work with browsers as they evolve.

Why PhoneGap?
Mobile app is next regeneration of development work. There are several Mobile OS currently available in the world competition market; Android, IOS, Bada, Blackberry, Symbian, WebOS and Window Phone.

To build an application each platform is required an adequate knowledge and skill for specific platform.
For example, if you want to build application for Android Platform you might have enough knowledge skill on Java. Also for IOS you might need a strong understanding on Objective-C and Coca framwork to applications for IOS platform…etc.

With PhoneGap does not require extra skill that you have already learned since Bachelor degree, they are HTML, Javascript and CSS. It can compile to a native application of your choices of platform.

Practice.
The practice here I will show about developing native app in Android with Eclipse.
Download PhoneGap here : http://www.phonegap.com


After download Eclipse and install Android SDK.
1.) Prepare the file structure as the following image.

2.) Write some few code in the main activity as below:


Here is a result:

Finally it is done. It is simple, right?
You can try yourself for IOS or Window Phone and other platform.