Aspect Oriented Programming For Eclipse Plug-ins

It seems to me that Aspect Oriented Programming never really took off when it was introduced. However, it’s a useful way to intercept, or analyse, methods as they happen, in an independent way.  Eclipse has a useful suite of AspectJ tools that you can download for your Eclipse installlation. Paired with the benefits of Eclipse’s plug-in system, aspects are a nice way of intercepting your RCP application.

The following instructions show how to get up and running with aspects in the Plug-in Development Environment really quickly. Once you have downloaded the Eclipse AspectJ tools, you will also want to include the Equinox Aspect jars in your plug-ins directory. The plug-ins you will need are org.eclipse.equinox.weaving.aspectj andorg.eclipse.equinox.weaving.hook

  1. Create a new OSGi plug-in:
  2. Right click on the project and choose AspectJ Tools/Convert to AspectJ Project
  3. Create a new package within the plugin eg. com.dzone.aspects.aspectTest
  4. Make a new aspectj Aspect within the package e.g. MyAspect
  5. In your manifest.mf export the package created in the previous step
    Export-Package: com.dzone.aspects
  6. A you write your AspectJ code, you will be advising another plug-in (for example org.eclipse.jdt.junit) You’ll need to do some extra setup in order to advise other plug-ins, by adding the following to your Aspect plug-in manifest.mf.
    Eclipse-SupplementBundle: org.eclipse.jdt.junit

    Note you can only supplement one bundle in an aspect. Therefore, if you want to crosscut another bundle, you’ll need to create a new AspectJ plug-in.

  7. It also helps to add the plugin that you are advising (org.eclipse.jdt.junit) to your aspect plugin’s dependencies. If you don’t do it you will get lint warnings from the AspectJ compiler
  8. In your plugins META-INF directory make a file called aop.xml, consisting of content similar to the following
    <?xml version="1.0" encoding="UTF-8"?>
    <aspectj>
        <aspects>
            <aspect
                name="com.dzone.aspects.aspectTest.MyAspect" />
        </aspects>
        <weaver options="-verbose"/>
    </aspectj>
  9. When executing use the following VM arguments in your Run Configuration
    -Dosgi.framework.extensions=org.eclipse.equinox.weaving.hook
    
    -Dorg.aspectj.osgi.verbose=true

It’s as simple as that. Have you any instructions to add to this?

Effective Debugging: Conditional Breakpoints

One of the most important developer activities is debugging. In my college days, we were forced to use simple text editors for our software development, so I started out using print statements to see where my code was going wrong. These days, we have the comfort of IDEs, but debugging remains one of those talents that you get more efficient at with experience.

The best feature I have seen in both Eclipse and NetBeans is the conditional breakpoint concept. The idea is simple, take your breakpoint, and type in a condition for the breakpoint to stop at. For example if I have the following code:

for(Employee emp: employees)
{
   if(emp.getType() == Employee.MANAGER)
   {
     addToManagers(emp);
   }
}

Let’s say that I want to see the values of all the variables when the employee’s getType value is Employee.DEVELOPER, and step through to make sure that we don’t enter the if statement block.

In Eclipse, you can set the breakpoint as normal on the if statement, right click on the breakpoint and you’ll see the following menu:

You can now set a condition for your breakpoint in the resulting dialog by selecting the Enable Condition checkbox:
As you type in the condition you get full content assist. You can also change what this condition means – whether to stop when it’s true, or when it changes since the last iteration.
In NetBeans, it’s much the same. You still get the properties on right-click of the breakpoint:
The dialog is also similar with conditions and hit count, with content assist:
Things like this can really help speed up your debugging – when you know a particular value has caused your program to fail, you can get right to the heart of the matter.

I Don’t Write Unit Tests Because…. : The Excuses

As someone who’s seen the benefits of the approach, I’m a huge believer in test driven development. It adds a level of quality and maturity to the field of software development, yet it’s still not a widespread practice across development projects. When it comes to a choice between the features, time and quality, it’s always the quality that suffers. We don’t want to add extra time for testing and we don’t want to compromise on the feature set of the delivery. If you haven’t set out to do test driven development at the start of the phase, then it’s difficult to fit in.

We’ve all heard excuses for not taking the test driven approach, but nowhere compiles them better than “Pragmatic Unit Testing in Java With JUnit“, from the Pragmatic Bookshelf.  I read the book a few years ago, and afterward I thought there was no way that any responsible developer could read the book without truly believing that unit tests were one of the most important aspects of the development activity.

The most worrying excuse I’ve heard is that it’s too difficult to test my code. This can be for one of two reasons. One is that your code is mainly UI related, and automating the UI tests is too difficult. I’ll concede that UI automation is a tricky area (but not impossible, as we’ll see in a later article), but every effort should be made to automate it if possible: think about regression tests. If you have a fully automated test suite, including the UI behaviour, you can make a change to your code, and have full confidence that you haven’t broken anything if you have tests to re-run.

The second reason that your code is too difficult to test is that you’ve messed up your design. Maybe your logic and UI code are too tightly coupled, and without that automated UI layer existing, the dependency between the logic and the UI will cause a problem. This is where test driven development helps to ensure a clean design, following best practices. Using JUnit is simple, so if I can just point my test at a clean logic layer, I can test all logic that the UI will ever touch.  What’s that? You’re missing your data model? Well then just use mock objects – there are many frameworks for that!

For those who haven’t read the book yet, I’ll give a quick summary of the excuses for not testing as outlined in the introduction chapter:

  • It takes too much time to write tests
    As the number one reason that developers give, and thinking back on my own education, I think this is down to the way computer science is taught. For the most part, we’re lead to believe that testing happens at the end of the process, not all the way through. 

    Pragmatic Unit Testing encourage the “pay as you go” model, where having tests written as you are developing means that you don’t have that crunch time at the end where you try to cram all your unit tests in.

    Anyway, if you’re not writing tests as you go along, how are you checking if the code behaves as you expect? You run it manually? Wouldn’t it make sense to invest some of that manual testing time into writing a JUnit test for it? I mean you’ll have to run that piece of code again sometime – it’s not going to remain untouched for the lifetime of the product.

    In fact, there are many more time penalties that happen if you don’t write unit tests. You’ll have to spend time debugging code trying to work out why something doesn’t work. Or you’ll refactor the code, and then find that nothing works as it used to after the refactor. If you had the unit tests written, you have a base of confidence.

  • It takes too long to run the tests
    I’ll admit, there can be a good amount of time taken running tests that involve external entities, or the user interface. But you’re supposed to have more than one level of test. The unit level tests should run quickly, and there may be a level of integration tests that can run without a big time impact. If there are higher level integration tests that are taking time, just run them less frequently – maybe even in a nightly build. That’s not to say you should ignore the lower level unit tests. These should always run fast enough that it becomes a natural part of your own development process.
  • It’s not my job to test code
    I don’t know at what stage a software developer decides that he can just throw code over the wall. If your job title was simple Coder than maybe there’s an excuse. But as your job is to develop working software, you need to be able to say that your code is functional.  The book makes a good point that if the QA development finds it difficult to find bugs in your code, it will do wonders for your reputation.
  • I don’t really know how the code is supposed to behave so I can’t test it
    This is a difficult one to react to without incredulity. If you don’t know how the code is supposed to behave, you shouldn’t have started writing it. You need to understand the requirements first.

There are a few more excuses listed in the book, but these are the main ones. What are the excuses that you’ve heard for not writing tests.

Write Your Good Code First

Writing good code first is a pretty obvious statement, but I’m not sure if people do this. In fact, I think that we make excuses all the time so that we don’t have to.

While catching up on Twitter recently, I checked what@UncleBob (Robert Martin, author of Clean Code) has been saying. Obviously he’s a smart guy, as pragamatic as they get, and always has useful insightful things to say. Here’s the tweet that caught my attention:

I’m sure most developers would say that they write good code, always. Think about it? Do you? I know I’ve definitely compromised my quality standards in the past, deciding that it’s better to “fix that later” rather than to get it right first time. The minute you do that, you’ve broken a window.

While on this topic of writing good code first, you might wonder where refactoring fits (but I hope that you’re not wondering!). Refactoring is inevitable, but what really gets me is when refactoring needs to be put down as a separate task in a project schedule. Looks like UncleBob would agree:

So why does it happen?  To me, seeing refactoring in the schedule is an admission that “you’re not going to get it right first time, so we’ll add in this extra time to fix it later”. Surely if there is a concern that the time allocated to a task doesn’t cover a complete, clean implementation, the task needs more time. Refactoring is a good thing, but you have to refactor as you go. Don’t commit too much code littered with //TODO comments, do it now.

Having refactor seen as a different task is the same as breaking down each feature into a list of tasks like design, unit test, code, refactor, test. Software developers should know what they need to do in order to produce quality software. The “task” is not just the coding part – it’s everything around it.

 

 

Creating Better Presentations

Creating presentations is a skill that is often overlooked by software developers, but it can be one of the most important parts of a developers toolbox. Getting a clear message across to your colleagues or management is vital. Of course, if you plan on presenting at a conference, writing a good presentation is even more important. The following set of slides from @jessedee, give a great set of tips to presenters:

STEAL THIS PRESENTATION!
View more presentations from @JESSEDEE

One of the tips highlighted here is that Powerpoint, or at least the templates that you get from Powerpoint, forces your presentation into a boring format. It’s something that we’ve all seen – too many bullet points and too much text. This leads to the audience doing more reading than listening. When it gets to this stage, you wonder why not just send around a document.

Another great resource for aspiring presenters is Presentation Zen. Steve Jobs is always quoted as an example of a great presenter.

Everything mentioned so far is fine more marketting or high level presentations. A lot of developers think that a technical presentation can’t conform to the above rules. But why not? You should still get the point across with an impressive visual presentation – the idea is to inspire people, or to convince them that you know what you’re talking about. Supporting documentation can be provided to the audience after the presentation.

What tips have you got for creating brilliant presentations? Are there any examples you’d like to share to highlight the very good (and the very bad!).

Design Patterns Uncovered: The Abstract Factory Pattern

Having gone through the Factory Method pattern in the last article in this series, today we’ll take a look at Abstract Factory, the other factory pattern.

Factories in the Real World

It’s easy to think of factories in the real world – a factory is just somewhere that items gets produced such as cars, computers or TVs. Wikipedia’s definition of a real world factory is:

A factory (previously manufactory) or manufacturing plant is an industrial building where workers manufacture goods or supervise machines processing one product into another.

It’s pretty clear what a factory does, so how does the pattern work?

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Abstract Factory Pattern

The Abstract Factory is known as a creational pattern – it’s used to construct objects such that they can be decoupled from the implementing system. The definition of Abstract Factory provided in the original Gang of Four book on Design Patterns states:

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Now, let’s take a look at the diagram definition of the Abstract Factory pattern.

Although the concept is fairly simple, there’s a lot going on in this diagram. I’ve used red to note the different between what ConcreteFactory2 is responsible for.

The AbstractFactory defines the interface that all of the concrete factories will need to implement in order to product Products. ConcreteFactoryA and ConcreteFactoryB have both implemented this interface here, creating two seperate families of product. Meanwhile, AbstractProductA and AbstractProductB are interfaces for the different types of product. Each factory will create one of each of these AbstractProducts.

The Client deals with AbstractFactory, AbstractProductA and AbstractProductB. It doesn’t know anything about the implementations. The actual implementation of AbstractFactory that the Client uses is determined at runtime.

As you can see, one of the main benefits of this pattern is that the client is totally decoupled from the concrete products. Also, new product families can be easily added into the system, by just adding in a new type of ConcreteFactory that implements AbstractFactory, and creating the specific Product implementations.

For completeness, let’s model the Clients interactions in a sequence diagram:

While the class diagram looked a bit busy, the sequence diagram shows how simple this pattern is from the Clients point of view. The client has no need to worry about what implementations are lying behind the interfaces, protecting them from change further down the line.

Where Would I Use This Pattern?

The pattern is best utilised when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details. As you’ll have noticed, a key characteristic is that the pattern will decouple the concrete classes from the client.

An example of an Abstract Factory in use could be UI toolkits. Across Windows, Mac and Linux, UI composites such as windows, buttons and textfields are all provided in a widget API like SWT. However, the implementation of these widgets vary across platforms. You could write a platform independent client thanks to the Abstract Factory implementation.

So How Does It Work In Java?

Let’s take the UI toolkit concept on to our Java code example. We’ll create a client application that needs to create a window.

First, we’ll need to create our Window interface. Window is our AbstractProduct.

//Our AbstractProduct
public interface Window
{

    public void setTitle(String text);

    public void repaint();
}

Let’s create two implementations of the Window, as our ConcreteProducts. One for Microsoft Windows:

//ConcreteProductA1
public class MSWindow implements Window
{
   public void setTitle()
  {
     //MS Windows specific behaviour
  }

   public void repaint()
  {
     //MS Windows specific behaviour
  }
}

And one for Mac OSX

//ConcreteProductA2
public class MacOSXWindow implements Window
{
   public void setTitle()
  {
     //Mac OSX specific behaviour
  }

   public void repaint()
  {
     //Mac OSX specific behaviour
  }
}

Now we need to provide our factories. First we’ll define our AbstractFactory. For this example, let’s say they just create Windows:

//AbstractFactory
public interface AbstractWidgetFactory
{
   public Window createWindow();
}

Next we need to provide ConcreteFactory implementations of these factories for our two operating systems. First for MS Windows:

//ConcreteFactory1
public class MsWindowsWidgetFactory
{
   //create an MSWindow
   public Window createWindow()
   {
      MSWindow window = new MSWindow();
      return window;
   }
}

And for MacOSX:

//ConcreteFactory2
public class MacOSXWidgetFactory
{
   //create a MacOSXWindow
   public Window createWindow()
   {
      MacOSXWindow window = new MacOSXWindow();
      return window;
   }
}

Finally we need a client to take advantage of all this functionality.

//Client
public class GUIBuilder
{
   public void buildWindow(AbstractWidgetFactory widgetFactory)
   {
      Window window = widgetFactory.createWindow();
      window.setTitle("New Window");
   }
}

Of course, we need some way to specify which type of AbstractWidgetFactory to our GUIBuilder. This is usually done with a switch statement similar to the code below:

public class Main{
   public static void main(String[] args)
   {
     GUIBuilder builder = new GUIBuilder();
     AbstractWidgetFactory widgetFactory = null;
     //check what platform we're on
     if(Platform.currentPlatform()=="MACOSX")
     {
        widgetFactory  = new MacOSXWidgetFactory();
     }
     else
     {
           widgetFactory  = new MsWindowsWidgetFactory();
     }
     builder.buildWindow(widgetFactory);
    }
}

Just to give a clear idea of how this implementation relates to the Abstract Factory pattern, here’s a class diagram representing what we’ve just done:

Watch Out for the Downsides

While the pattern does a great job of hiding implementation details from the client, there is always a chance that the underlying system will need to change. We may have new attributes to our AbstractProduct, or AbstractFactory, which would mean a change to the interface that the client was relying on, thus breaking the API.

With both the Factory Method and today’s pattern, the Abstract Factory, there’s one thing that annoys me – someone has to determine what type of factory the client is dealing with at runtime. As you see above, this is usually done with some type of switch statement.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Factory Method Pattern

This article will focus on the Factory Method pattern, a variation on the simple factory. The Factory, as it’s name suggests, is a pattern used to facilitate the creation of other objects. In a later article we’ll be looking at the AbstractFactory.

Factories in the Real World

It’s easy to think of factories in the real world – a factory is just somewhere that items gets produced such as cars, computers or TVs. Wikipedia’s definition of a real world factory is:

A factory (previously manufactory) or manufacturing plant is an industrial building where workers manufacture goods or supervise machines processing one product into another.

It’s pretty clear what a factory does, so how does the pattern work?

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Factory Method Pattern

Factory Method is known as a creational pattern – it’s used to construct objects such that they can be decoupled from the implementing system. The definition of Factory Method provided in the original Gang of Four book on Design Patterns states:

Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses

Now, let’s take a look at the diagram definition of the Factory Method  pattern. The Creator hides the creation and instantiation of the Product from the client. This is a benefit to the client as they are now insulated from any future changes – the Creator will look after all of their creation needs, allowing to decoupling. Furthermore, once the Creator and the Product conform to an interface that the client knows, the client doesn’t need to know about the concrete implementations of either. The factory method pattern really encourages coding to an interface in order to deal with future change.

Factory Method Pattern

Here the Creator provides an interface for the creation of objects, known as the factory method. All other methods in our abstract Creator are written only to operate on the Products created in the ConcreteCreator. The Creator doesn’t create the products – that work is done by it’s subclasses, such as ConcreateCreator.

Now let’s take a look at a sequence diagram to see how this pattern behaves:

Factory Sequence Diagram

Here we see the client making a call to the abstract Creator, which then uses the factoryMethod() to get a new instance of the ConcreteProduct, complete’s the anOperation() method and completes.

Where Would I Use This Pattern?

The idea behind the Factory Method pattern is that it allows for the case where a client doesn’t know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job. The FactoryMethod builds on the concept of a simple Factory, but lets the subclasses decide which implementation of the concrete class to use.  You’ll see factories used in logging frameworks, and in a lot of scenarios where the client doesn’t need to know about the concrete implementations. It’s a good approach to encapsulation.

So How Does It Work In Java?

This example will use the concept of a logger to illustrate the factory method. First, let’s create our Product interface, in this case Logger:

//interface (Product)
public interface Logger {

	public void log(String message);
}

Next we’ll create one ConcreteProduct named XMLLogger. Obviously, we would have many different loggers

//concrete implementation of the Logger (Product)
public class XMLLogger implements Logger {

	public void log(String message) {
		//log to xml
		System.err.println("logging");
	}

}

Next, we’ll create our Creator, as a class with an abstract method that the concrete creator subclasses need to implement:

//the abstract Creator
public abstract class AbstractLoggerCreator
{
	//the factory method
	public abstract Logger createLogger();

	//the operations that are implemented for all LoggerCreators
	//like anOperation() in our diagram
	public Logger getLogger()
	{
		//depending on the subclass, we'll get a particular logger.
		Logger logger = createLogger();

		//could do other operations on the logger here

		return logger;
	}

}

The XMLLoggerCreator is our ConcreteCreator

//ConcreteCreator
public class XMLLoggerCreator extends AbstractLoggerCreator{

	@Override
	public Logger createLogger() {
		XMLLogger logger = new XMLLogger();
		return logger;
	}

}

Here’s the client code to test drive our implementation of the pattern:

public class Client {
	private void someMethodThatLogs(AbstractLoggerCreator logCreator)
	{
		Logger logger = logCreator.createLogger();
		logger.log("message");

	}

	public static void main(String[] args)
	{
		//for the purposes of this example, create an XMLLoggerCreator directly,
		//but this would normally be passed to constructor for use.
		AbstractLoggerCreator creator = new XMLLoggerCreator();

		Client client = new Client();
		client.someMethodThatLogs(creator);
	}

}

As you can see, someMethodThatLogs, takes any AbstractLoggerCreator depending on who calls the method. So, if we wanted to log to a file, or the console, we would pass through the appropriate AbstractLoggerCreator implementations.

One thing that I have left out here is the possibility to pass a paramater through to the creator in order to choose which type of concrete class to create. For example, we could have made FileLoggerCreator that could take a string parameter, allowing us to choose between XML and flat files.

Watch Out for the Downsides

One thing I would note about this approach to the Factory is that it might be overcomplicated. Perhaps the Abstract Factory is a better approach for creating objects in a decoupled manner. We’ll be discussing the Abstract Factory pattern next in the series, and will compare the two approaches then. If you want to create your own particular type of “Product” you would probably need to subclass a Creator. As with all design patterns, use it with caution, and make sure you need it.

In a lot of cases, a simple factory pattern will work fine. The FactoryMethod  just allows further decoupling, leaving it to the subclasses of the Creator to decide which type of concrete Product to create.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Command Pattern

Today’s pattern is the Command, which allows the requester of a particular action to be decoupled from the object that performs the action. Where the Chain of Responsibility pattern forwarded requests along a chain, the Command pattern forwards the request to a specific module.

Command in the Real World

One example of the command pattern being executed in the real world is the idea of a table order at a restaurant: the waiter takes the order, which is a command from the customer.This order is then queued for the kitchen staff.  The waiter tells the chef that the a new order has come in, and the chef has enough information to cook the meal.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Command Pattern

The Command pattern is known as a behavioural pattern, as it’s used to manage algorithms, relationships and responsibilities between objects. The definition of Command provided in the original Gang of Four book on Design Patterns states:

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations

So what does this mean in a class diagram?

Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation. The Receiver has the knowledge of what to do to carry out the request.  The Invoker holds a command and can get the Command to execute a request by calling the execute method. The Client creates ConcreteCommands and sets a Receiver for the command. The ConcreteCommand defines a binding between the action and the receiver. When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver.

The following sequence diagram shows the relationship in a clearer way:

If this all seems a bit confusing right now, hang on for the code example later on in the article.

When Would I Use This Pattern?

The Command Pattern is useful when:

  • A history of requests is needed
  • You need callback functionality
  • Requests need to be handled at variant times or in variant orders
  • The invoker should be decoupled from the object handling the invocation.

You’ll see command being used a lot when you need to have multiple undo operations, where a stack of the recently executed commands are maintained. To implement the undo, all you need to do is get the last Command in the stack and execute it’s undo() method.

You’ll also find Command useful for wizards, progress bars, GUI buttons and menu actions, and other transactional behaviour.

So How Does It Work In Java?

Let’s use a remote control as the example. Our remote is the center of home automation and can control everything. We’ll just use a light as an example, that we can switch on or off, but we could add many more commands.

First we’ll create our command interface:

//Command
public interface Command
{
    public void execute();
}

Now let’s create two concrete commands. One will turn on the lights, another turns off lights:

//Concrete Command
public class LightOnCommand implementsCommand
{
    //reference to the light
    Light light;

    public LightOnCommand(Light light)
    {
        this.light = light;
    }

    public void execute()
    {
        light.switchOn();
    }

}
 //Concrete Command
public class LightOffCommand implementsCommand
{
    //reference to the light
    Light light;

    public LightOffCommand(Light light)
    {
        this.light = light;
    }

    public void execute()
    {
        light.switchOff();
    }

}

Light is our receiver class, so let’s set that up now:

//Receiver
public class Light
{
   private boolean on;

   public void switchOn()
   {
      on = true;
   }

   public void switchOff()
   {
      on = false;
   }

}

Our invoker in this case is the remote control.

//Invoker
public class RemoteControl
{
    private Command command;

    public void setCommand(Command command)
    {
        this.command = command;
    }

    public void pressButton()
    {
        command.execute();
    }

}

Finally we’ll set up a client to use the invoker

//Client
public class Client
{
    public static void main(String[] args)
    {
        RemoteControl control = new RemoteControl();

        Light light = new Light();

        Command lightsOn = new LightsOnCommand(light);
        Command lightsOff = new LightsOffCommand(light);

        //switch on
        control.setCommand(lightsOn);
        control.pressButton();

        //switch off
        control.setCommand(lightsOff);
        control.pressButton();

    }

}

Watch Out for the Downsides

This pattern ends up forcing a lot of Command classes that will make your design look cluttered – more operations being made possible leads to more command classes. Intelligence required of which Command to use and when leads to possible maintainence issues for the central controller.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

//Client
public class Client
{
    public static void main(String[] args)
    {
        RemoteControl control = new RemoteControl();

        Light light = new Light();

        Command lightsOn = new LightsOnCommand(light);
        Command lightsOff = new LightsOffCommand(light);

        //switch on
        control.setCommand(lightsOn);
        control.pressButton();

        //switch off
        control.setCommand(lightsOff);
        control.pressButton();

    }

}

Design Patterns Uncovered: The Chain Of Responsibility Pattern

Today’s pattern is the Chain of Responsibility, a simple way to decouple the handling of requests.

Chain of Responsibility in the Real World

The idea of the Chain Of Responsibility is that it avoids coupling the sender of the request to the receiver, giving more than one object the opportunity to handle the request.  This process of delegation appears quite frequently in the real world where there is one interface for the customer to go through. One example could be a bank, where an application that you send in to the bank branch may be handled by one particular department. Another example is a vending machine, where you can put in any coin, but the coin is passed on to the appropriate receptacle to determine the amount that the coin is worth. 

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Chain of Responsibility Pattern

The Chain of Responsibility is known as a behavioural pattern, as it’s used to manage algorithms, relationships and responsibilities between objects. The definition of Chain of Responsibility provided in the original Gang of Four book on Design Patterns states:

Gives more than one object an opportunity to handle a request by linking receiving objects together.

Chain of Responsibility allows a number of classes to attempt to handle a request, independently of any other object along the chain. Once the request is handled, it completes it’s journey through the chain.

Let’s take a look at the diagram definition before we go into more detail.

The Handler defines the interface required to handle request, while the ConcreteHandlers handle requests that they are responsible for.  If the ConcreteHandler cannot handle the request, it passes the request onto it’s successor, which it maintains a link to.

The objects in the chain just need to know how to forward the request to other objects.  This decoupling is a huge advantage, as you can change the chain at runtime.

Would I Use This Pattern?

This pattern is recommended when either of the following scenarios occur in your application:

  • Multiple objects can handle a request and the handler doesn’t have to be a specific object
  • A set of objects should be able to handle a request with the handler determined at runtime
  • A request not being handled is an acceptable outcome.

The pattern is used in windows systems to handle events generated from the keyboard or mouse. Exception handling systems also implement this pattern, with the runtime checking if a handler is provided for the exception through the call stack. If no handler is defined, the exception will cause a crash in the program, as it is unhandled.

In JavaEE, the concept of Servlet filters implement the Chain of Responsibility pattern, and may also decorate the request to add extra information before the request is handled by a servlet.

So How Does It Work In Java?

Now let’s take a look at how we might implement the Chain of Responsibility with a code example. Let’s use an email client as an example. You might set up some rules to move a message into a particular folder depending on who it’s from. First we’ll need to create our EmailHandler interface.

//Handler
public interface EmailHandler
{
	//reference to the next handler in the chain
	public void setNext(EmailHandler handler);

	//handle request
	public void handleRequest(Email email);
}

Now let’s set up two concrete handlers, one for business mail and one for email originating from Gmail. These handlers pass on the request if it doesn’t interest them

public class BusinessMailHandler implements EmailHandler
{
	private EmailHandler next;

	public void setNext(EmailHandler handler)
	{
	    next = handler;
	}

	public void handleRequest(Email email)
    {
		if(!email.getFrom().endsWith("@businessaddress.com")
		{
		    next.handleRequest(email);
		}
		else
		{
		    //handle request (move to correct folder)
		}

	}	

}
public class GMailHandler implements EmailHandler
{
	private EmailHandler next;

	public void setNext(EmailHandler handler)
	{
	    next = handler;
	}

	public void handleRequest(Email email)
    {
		if(!email.getFrom().endsWith("@gmail.com")
		{
		    next.handleRequest(email);
		}
		else
		{
		    //handle request (move to correct folder)
		}

	}	

}

Now let’s set up a client that manages the handlers – this will actually be our EmailProcessor.

public class EmailProcessor
{
	//maintain a reference to the previous handler so we can add the next one
	private EmailHandler prevHandler;

	public void addHandler(EmailHandler handler)
	{
		if(prevHandler != null)
		{
			prevHandler.setNext(handler);
		}
		prevHandler = handler;
	}

}

This class allows us to add in new handlers at any stage. Finally, the email client itself uses the EmailProcessor to look after all incoming messages

//email client 

public class EmailClient
{
	private EmailProcessor processor; 

	public EmailClient()
	{
	   createProcessor();

	}

	private void createProcessor()
	{
		processor = new EmailProcessor();
		processor.addHandler(new BusinessMailHandler());
		processor.addHandler(new PersonalMailHandler());
	}

	public void addRule(EmailHandler handler)
	{
	   processor.addHandler(handler);
	}

	public void emailReceived(Email email)
	{
		processor.handleRequest(email);
	}

	public static void main(String[] args)
	{

		EmailClient client = new EmailClient();

	}

}

If new rules, for forwarding email to particular folders are added, we can add the handler to our email processor at runtime using the addRule() method in the client.

Watch Out for the Downsides

As with the Observer pattern, Chain of Responsibility can make it difficult to follow through the logic of a particular path in the code at runtime. It’s also important to note that there is the potential that the request could reach the end of the chain and not be handled at all.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Inspiration For Your Mobile Applications

So you know exactly what you want your mobile application to do, but you’re not sure how to design the screens.  Usually, there’s an app out there that’s done something similar. I found two great sites that provide screenshots of popular mobile applications, providing ideas for everything from splash screens to profile pages, lists to sign-up flows.

Both sites are worth bookmarking for those times when inspiration dries up.