The Most Popular Language This Month Is….

The most popular language of this month? Well it depends which source you use. For example, I checked out the TIOBE index as well as the top language used in GitHub projects. Would you be surprised that Java was not number 1 on either listing?

Now, I never take these language popularity things too seriously. More than likely, the language you’re using at work isn’t the cool language of the day. But it gives a good indication of what languages might be worth learning, if you have the time.

TIOBE Index – C Reigns Supreme

On the TIOBE index, where Java has been number one for a very very long time, C has taken it’s place at the top. Yes, C!

Don’t worry if you’re confused right now looking at this – I don’t get it either! It’s obvious that Objective-C continues to grow more popular. But JavaScript looks a bit low on this index, especially when you consider the results I found at GitHub

GitHub  – Everybody Loves JavaScript

I guess the GitHub ratings make more sense, considering you can’t move in GitHub without bumping into a JavaScript project. Every other language has a reasonable showing. Compare Java to C and there’s not much in it.

Some Better News For Java Developers

I didn’t have to go too far to find some good news for Java developers. RoleConnect, an Irish company that connects contractors with employers ran some analysis on what skills are most in demand right now. According to the team there, there’s still a huge interest in Java/J2EE and Spring developers.

So, three different indices and it’s no clearer what the most popular language really is. Is there a definitive way to measure this statistic? Or is it just all too subjective?

Getting To Grips With the Equinox Console

When developing Eclipse RCP applications, sometimes you’ll find that your plug-in’s capabilities don’t seem to available. The Equinox OSGi console is one of the most useful tools to inspect the state of all the plug-ins in a running application. This article gives a brief introduction to the console, and how it can be used to help with your development of an OSGi based system.

To make the console available, just use the -console parameter in your run configuration. If you want to see the console for an “installed” Eclipse instance, you can just add -console to the list of parameters for running Eclipse (e.g. eclipse.exe -console). Having done that you’ll see osgi> appear in the console output, similar to an MS-DOS window.

The following is a list of commands that can be used in the osgi console:

  • help
    Lists all available commands.

  • ss
    Provides a list of all the plug-ins and their current status. If you provide a string after ss, it will list all bundles containing that name. For example, if I used ss logging I would be presented with a list of plug-ins that contain logging in their name. ss here stands for short status.
  • start
    Starts up a plug-in. You can either pass through the full name of the plug-in to this command, or else you can use the symbolic id, as displayed from the previous ss command.
  • stop
    Stops a plug-in. Just like the start command, you can either pass through the full name of the plug-in or the symbolic id.
  • install
    Paired with a URL , this installs the plug-in that the URL refers to into your system. There is also an updatecommand, that allows you to update a plug-in using a URL.
  • uninstall
    This command takes the symbolic id of a plug-in and uninstalls it from your running system
  • diag
    Using the symbolic id, or the plug-in name, this command shows all resolution problems for a particular plug-in.

  • active
    Lists all the active plug-ins in the running system.

So when you have an issue with your plug-in:

  • Make sure it’s on the list of bundles, using the ss command. Or if you expect the plug-in to be running, use the activecommand.
  • Using the id of your plug-in (usually easier than typing in the full name) check that the status of your plug-in is  ACTIVE. If not maybe you need to force the plug-in to start up using the start command.

Once you become familiar with the OSGi console, it becomes a very powerful utility for investigating the overall status of your OSGi based application.

Design Patterns Uncovered: The Mediator Pattern

Today’s pattern is the Mediator pattern, used to handle complex communications between related objects, helping with decoupling of those objects.

Mediator in the Real World

An airport control tower is an excellent example of the mediator pattern. The tower looks after who can take off and land – all communications are done from the airplane to control tower, rather than having plane-to-plane communication. This idea of a central controller is one of the key aspects to the mediator pattern.

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 Mediator Pattern

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

Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other.  Allows for the actions of each object set to vary independently of one another.

The following diagram shows how the mediator pattern is modelled.

The Mediator defines the interface for communication between Colleague objects. The ConcreteMediator implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all the Colleagues and their purpose with regards to inter communication. The ConcreteColleague communicates with other colleagues through the mediator.

Without this pattern, all of the Colleagues would know about each other, leading to high coupling. By having all colleagues communicate through one central point we have a decoupled system while maintaining control on the object’s interactions.

When Would I Use This Pattern?

The mediator is a good choice of pattern when the communication between objects is complicated, but well defined. When there are too many relationships between the objects in your code, it’s time to think of having such a central point of control.

An observer based variation of the mediator pattern is used in Java Message Service (JMS) implementations, which allows applications to subscribe and publish data to other applications. This is a common combination of patterns that makes sense.

So How Does It Work In Java?

Here we’ll use the Mediator pattern in the context of a chatroom application. First we’ll define an interface for our mediator

//Mediator interface
public interface Mediator
{
	public void send(String message, Colleague colleague);
}

While we described the Colleague as an interface above, it’s more useful to use an abstract class in this case:

//Colleage interface
public abstract Colleague
{
	private Mediator mediator;

	public Colleague(Mediator m)
	{
	    mediator = m;
	}

	//send a message via the mediator
        public void send(String message)
	{
	   mediator.send(message, this);
	}

	//get access to the mediator
	public Mediator getMediator()
	{
		return mediator;
	}

        public abstract void receive(String message);	

}

Now let’s create our concrete mediator implementation

public class ApplicationMediator implements Mediator
{
	private ArrayList<Colleague> colleagues;

        public ApplicationMediator()
        { colleagues = new ArrayList<Colleague>();} 

        public void addColleague(Colleague colleague)
        { colleagues.add(colleague);}

	public void send(String message, Colleague originator)
	{
		//let all other screens know that this screen has changed
		for(Colleague colleague: colleagues)
		{
			//don't tell ourselves
			if(colleague != originator)
			{
				colleage.receive(message);
			}
		}

	}

}

Finally we’ll create one concrete colleage.

public class ConcreteColleague extends Colleague
{
      public void receive(String message)
        {
           System.out.println("Colleague Received: " + message);
       }	

}

Here’s a client that drives the entire application:

public class Client
{
  public static void main(String[] args)
  {
      ApplicationMediator mediator = new ApplicationMediator(); 

     ConcreteColleague desktop = new ConcreteColleague(mediator)
     ConcreteColleague mobile = new MobileColleague(mediator)

      mediator.addColleague(desktop);
      mediator.addColleague(mobile);

      desktop.send("Hello World");
      mobile.send("Hello"); 

  }
}

Watch Out for the Downsides

While this pattern aims to reduce complexity, without proper design, the Mediator object itself can become very complicated itself.The Observer pattern could help here, with the colleague objects dealing with the events from the mediator, rather than having the mediator look after all orchestration.

Find Out More


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

Maintaining Your Value In the Software Industry

These days it can be tough to find the job you want as a software developer, either because the lack of opportunities out there, or facing huge competition in the process. In this article, I’d like to offer some tips that  might help you to maintain your value as a software developer.

All of these tips apply to those who are in current employment, or who are looking for a job. If you aren’t working right now, some of these points are essential: you don’t want it to appear as if you’ve lost interest in software when you’re not getting paid for it!

Challenge Yourself

While you may think that you know all that you need to know, there’s no harm in expanding your experience and improving your CV by achieving some relevant certification.

Certification is a really effective way of learning new things and refreshing on the things you already know.  Java developers have huge certification options available through the Sun Java Certification exams. Starting off with the SCJP exam, you can choose the path that suits you, all the way to Enterprise Architect. Eclipse developers can earn RCP and OSGi certification through the Eclipse Training Alliance.

Stay Educated

If certification isn’t an option for your technology, or you’ve done it all before, make sure that at the very least you stay educated. This can be as simple as buying a book, or doing an online tutorial. As well as keeping up to date on technologies that you use, it’s really rewarding to educate yourself in a new framework or technology. Once again, your CV gets a nice update and you’ll probably find ways to apply what you’ve learned in your current job.

Training course can be expensive, but if you can afford it – go for it. Make sure that you do a sufficient amount of research into the course to make sure it suits your needs and covers what you expect.

However,once you know the basics of software development, it’s easy to teach yourself.  There’s a lot of information available out there, and a large amount of the tools and IDEs that you need are probably free.

Join A Community

If you have a local user group, or gathering of other technologists, why not try to go to the meetings once in a while? Maybe start up a local technology conference and work on your presentation skills.

If you’re out of work right now, joining an open source project can be of huge benefit. You get to work as a team with other people passionate about technology, and pick up new skills from them. More importantly, joining an open source project can fill that empty year in your CV, and show that you’ve kept your skills sharp.

Find Your Voice

Finally, starting up your own blog can really help your confidence. It’s never been easier to set up a blog, with so many providers available. Teaching can be the best way of learning – so as you write about the technologies, tools and frameworks that interest you, you’ll find that you have an even better understanding. Researching new topics for your blog can be really interesting too. The most rewarding part is when you find that you have an audience and people are interested in what you have to say.

I should point out here that we do have an MVB program here at DZone, which is a really effective way of getting traffic to your blog from the DZone platform.

The key point I’d like to make is that you should never stand still as a software developer – there’s always someone behind you who will pass you out. Have you any other tips to share on staying sharp?

Why Do I Break The Rules? And Who Can Stop Me?

I’ve been developing software for quite a few years now and I notice that sometimes I break the rules, those best practices that I know are right to follow.  With so many blogs, books and articles covering the best way to develop software, the temptation to do your own thing still can take over – even when you know it’s wrong.

Ashamedly, I know that I’ve broken these rules in the past, as I’m sure most software developers have.

Test Driven Development

There’s no question in my mind that the best approach to developing any piece of code is to do tests first and then code. It focussed the developer in a different way than other approaches. You’ll find that you start a fresh project with good intentions and write your tests first. Then, as you get further along the way, you start to run out of time, so somethings got to give – it will usually be your tests.

There’s no excuse for this. All IDEs have JUnit built in to them and any developer with experience knows that it works. All developers who think that unit tests can be skipped should read Pragmatic Unit Testing. The authors put it best when they proclaim “unit testing means never having to say you’re sorry“.

Ignoring Broken Windows

Sticking with the Pragmatic Programmer series of books, one of the big lessons for software development is to have “no broken windows”. A broken window is a piece of badly written code that exists in your codebase. If the window isn’t fixed, then it will lead to other broken windows.

While I might not be the first one to pollute a codebase, I’m as guilty as that person for not fixing, or at least logging, the issue. I don’t know how many times I’ve gone through code, looking for where I need to add in my fix, and ignored rows of broken windows on the way.

Once again, there’s no excuse for this – I’m aware of the rule, I know that it makes sense, but I’m too caught up in getting my part done.

Mixed Up Spagetti Code

These days most of us declare the wonders of modular architectures – being able to seperate code down to bundles of responsibility and redeploy those bundles anywhere. So we create a bundle (or package) with UI responsibilities, and then we create another for logic. How many times have you seen that logic code starts to creep into your UI bundle? Of course this doesn’t become apparent until too late unless you’ve been following a test driven development approach, and have been testing anything that you can do on the UI through the logic layer.

Of everything on this list, this is the one that I hate the most, and as such is the one that I’m least prone to.

Diving Right Into The Code

It’s new project day, and you know you’re going to be using some cool technologies. Even if you’re using the same technology, at least it’s a clean slate. Nothing of the past three habits is going to get in the way this time. Or will it?

The tendency to avoid analysis, and dive straight into the code is common with all developers. It’s a natural thing as we like to get things running. It’s even excusable if you do a quick run through, take the lessons learned and then go through an analysis stage. But it’s the going back that’s the problem – once we’re in the code, we’re happy there.  Sometimes we sugarcoat this as an “agile approach” but is it really?

The Solution

The software industry would be in a much better state if we had a ready made solution to these bad habits. There’s a common theme through all of my failures above, and that is time. Doesn’t it look like I’m always up against the clock? Maybe that’s my fault for not giving clear enough estimates. But if I bump up an estimate to ensure I follow all these rules, am I just going to waste the extra time I’m given?

Of course there are things that can be done such as peer reviews, but nothing can beat good programmer discipline. Maybe we need to introduce some kind of hippocratic oath for software developers?

 

Deadlines Revealed: The Truth About How We Make It Across The Line

Even though all software developers have the best of intentions, sometime we have to bend the rules a bit in order to make deadlines. In most cases these hacks don’t last too long in the codebase, although Microsoft are just getting around to fixing a 17 year old bug. One of the funniest and most original articles I’ve read, that relates to this topic is Gamasutra’s Dirty Programming Tricks. The article is basically a collection of nine pieces of trickery and hackery that people encountered in their programming career. It would be great to hear of your own experiences in the Java development world.

It’s not all hacks though. My favourite trick in there is The Programming Antihero. In this example the team are working on a project where the memory footprint has to be low. Unknowingly to the team who working tirelessy to save every megabyte they can, a senior developer has purposefully injected a wasteful 2MB to make the problem seem worse. Once everyone has got as close as they can to the target, he deletes the call putting the project back on track.

“…so he explained to me that he had put aside those two megabytes of memory early in the development cycle. He knew from experience that it was always impossible to cut content down to memory budgets, and that many projects had come close to failing because of it. So now, as a regular practice, he always put aside a nice block of memory to free up when it’s really needed.”

You’ll find lots of other examples throughout the article covering some shameful hacks to get around those last minute bugs. In my time I’ve had to write plenty of “this is a hack”, or “here be monsters” comments, to warn other developers about the dirty code that I’ve had to inject into my applications. I’ve had to put in Thread.sleep() to get around some problems. I’ve seen times that adding a System.out.println() allows the code to execute nicely, where removing it has caused things to break.  Don’t worry, I’ve gone back and debugged through these issues carefully and fixed them.

At deadline time, sometimes you just have to do whatever it takes. I’d like to hear your software development confessions here. I’m sure there’s no developer out there that hasn’t damaged their integrity briefly to get across the line.

Design Patterns Uncovered: The Iterator Pattern

Today’s pattern is the Iterator pattern which formalizes how we move through a collection of data in a particular class

Iterator in the Real World

MP3 player control is a good example of an iterator. The user doesn’t mind how to view their list of songs, once they get to see them somehow. In older mp3 players, this was done using simple forward and back buttons. With the iPod this changed to the wheel navigation concept. The iPhone moves this on further to use swipe movements. Nevertheless, the same idea is provided by all interfaces – a way to iterate through your music collection.

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 Iterator Pattern

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

Provides a way to access the elements of an aggregate object without exposing its underlying represenation.

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

The Aggregate defines an interface for the creation of the Iterator object. The ConcreteAggregate implements this interface, and returns an instance of the ConcreteIterator. The Iterator defines the interface for access and traversal of the elements, and the ConcreteIterator implements this interface while keeping track of the current position in the traversal of the Aggregate.

Using this pattern, you can build on the standard concept of iteration to define special iterators that only return specific elements in the data set.

Would I Use This Pattern?

This pattern is useful when you need access to elements in a set without access to the entire representation. When you need a uniform traversal interface, and multiple traversals may happen across elements, iterator is a good choice.

It also makes you code much more reasonable, getting rid of the typical for loop syntax across sections of your codebase.

So How Does It Work In Java?

Java provides an implementation of the Iterator pattern, which provides next() and hasNext() methods. Creation of the iterator in Java is typically done through a method named iterator() in the container class.
The following example shows use of an iterator with a list :

List<String> list = new ArrayList<String>();
//add strings 

Iterator it = list.iterator();
while(it.hasNext())
{
   String s = it.next();
}

Now let’s go to an example where we create the constructs ourselves, with a remote control example.
First we’ll create an iterator with the standard methods:

//Iterator interface
public interface ChannelIterator
{

	public boolean hasNext();

	public void next();

	public String currentItem();

}

Next we create the Aggregate interface, in this case a TV.

//Aggregate interface
public interface TV
{
	public Channel getIterator();
	//other TV methods
}

The concrete implementation of the aggregator has the capability to create the iterator

//Concrete Aggregator
public class ConcreteTV
{
	private ChannelIterator iterator;
	private List<String> channels; 

	public ConcreteTV()
	{
		iterator = new ConcreteChannelIterator(channels);
	}

	public ChannelIterator getIterator()
	{
		return iterator;
	}

}

Finally the iterator helps control how we navigate the data.

//Concrete Iterator
//Iterator interface
public interface ChannelIterator
{
	private List<String> channels; 

	private int currentPos = 0; 

	public ChannelIterator(List<String> channels)
	{
		this.channels = channels;
	}

	public boolean hasNext()
	{
		if(currentPos + 1 < channels.size())
		{
			return true;
		}
		return false;
	}

	public void next()
	{
		currentPos++;
	}

	public String currentItem()
	{
		return channels.get(currentPos);
	}

}

Of course this is a one-way remote control. We could implement back() and hasBack() methods to navigate backwards in our iterator.

Watch Out for the Downsides

I don’t see any disadvantages to this pattern. It’s simple, widely used and provides more readable code. However, you may disagree – if so, please let me know in the comments section.

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 Decorator Pattern

Today’s pattern is the Decorator pattern, which allows class behaviour to be extended dynamically at runtime.

Decorator in the Real World

The concept of a decorator is that it adds additional attributes to an object dynamically. A real world example of this would be a picture frame. The picture is our object, which has it’s own characteristics. For display purposes we add a frame to the picture, in order to decorate it. You’re probably already familiar with the concept of wrapper objects, and in essence, that is what a Decorator is.

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 Decorator Pattern

The Decorator is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Decorator provided in the original Gang of Four book on Design Patterns states:

Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviours

Traditionally, you might consider subclassing to be the best way to approach this – but there will be cases that subclassing isn’t possible, or is impractical. This leads us to the Open/Closed Principle: classes should be open for extension, but closed for modification. This is a good principle to keep in mind, as it keeps your class stable, but leaves it open for extension if someone wants to add behaviour.

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

The Component defines the interface for objects that can have responsibilties added dynamically, and the ConcreteComponent is simply an implementation of this interface. The Decorator has a reference to a Component, and also conforms to the  Component interface.  This is the important thing to remember, as the Decorator is essentially wrapping the Component. The ConcreteDecorator just adds responsibilities to the original Component.

Would I Use This Pattern?

The Decorator pattern should be used when:

  • Object responsibilities and behaviours should be dynamically modifiable
  • Concrete implementations should be decoupled from responsibilities and behaviours

As mentioned in the previous section, this can be done by subclassing. But too much subclassing is definitely a bad thing. As you add more behaviours to a base class, you will soon find yourself dealing with maintenance nightmare, as a new class is created for each possible combination. While the decorator can cause it’s own issues, it does provide a better alternative to too much subclassing.

So How Does It Work In Java?

You’ll see decorators being used in Java I/O streams. Stream classes extend the base subclasses to add features to the stream classes.

In our example, we’ll use emails to illustrate the Decorator.

First we have an email interface, which has a getContents method:

public interface IEmail
{
   public String getContents();

}

And we’ll provide a concrete implementation for use:

//concrete component
public class Email implements IEmail
{
   private String content;

   public Email(String content)
   {
      this.content = content;
   }

   @Override
   public String getContents()
   {
      //general email stuff
      return content;

   }

}

Now we’ll create a decorator which will wrap the base email with extra functionality. We’ll model this as an abstract class, and maintain a reference to the base email.

public abstract class EmailDecorator implements IEmail
{
   //wrapped component
   IEmail originalEmail;

}

Let’s say that emails that leave the company internal server need to have a disclaimer added to the end. We can just add in a decorator to handle this:

//concrete decorator
public class ExternalEmailDecorator extends EmailDecorator
{
   private String content; 

   public ExternalEmailDecorator(IEmail basicEmail)
   {
      originalEmail = basicEmail;
   }

   @Override
   public String getContents()
   {

      //  secure original
      content = addDisclaimer(originalEmail.getContents());
      return content;
   }

   private String addDisclaimer(String message)
   {
      //append company disclaimer to message
      return  message + "\n Company Disclaimer";
   }

}

And if we wanted to create secure, encrypted messages, we could use another decorator:

//concrete decorator
public class SecureEmailDecorator extends EmailDecorator
{
   private String content; 

   public SecureEmailDecorator(IEmail basicEmail)
   {
      originalEmail = basicEmail;
   }

   @Override
   public String getContents()
   {

      //  secure original
      content = encrypt(originalEmail.getContents());
      return content;
   }

   private String encrypt(String message)
   {
      //encrypt the string
      return  encryptedMessage;
   }

}

So, if our email sending client detects this message is going outside the company, we can invoke the appropriate decorator before sending:

public class EmailSender
{

   public void sendEmail(IEmail email)
   {
      //read the email to-address, to see if it's going outside of the company
      //if so decorate it
      ExternalEmailDecorator external = new ExternalEmailDecorator(email);
      external.getContents();
      //send 

   }
}

Watch Out for the Downsides

Overuse of the Open/Closed principle can lead to abstract and complex code. This principle should really only be used in places where code is least likely to change.

The Design Patterns book does point out a couple of disadvantages with this pattern. Decorators can lead to a system with a lot of smaller objects that will look similar to a developer and introduce a maintenance headache. Also, the Decorator and it’s enclosed components are not identical, so tests for object type (instanceof) will fail.

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 Proxy Pattern

Today’s pattern is the Proxy pattern, another simple but effective pattern that helps with controlling use and access of resources.

Proxy in the Real World

A Proxy can also be defined as a surrogate. In the real work a cheque or credit card is a proxy for what is in our bank account.  It can be used in place of cash, which is what is needed, and provides a means of accessing that cash when required. And that’s exactly what the Proxy pattern does – controls and manage access to the object they are “protecting”.

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 Proxy Pattern

The Proxy is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Proxy provided in the original Gang of Four book on Design Patterns states:

Allows for object level access control by acting as a pass through entity or a placeholder object.

So it’s quite a simple concept – to save on the amount of memory used, you might use a Proxy. Similarly, if you want to control access to an object, the pattern becomes useful.

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

As usual, when dealing with design patterns we code to interfaces. In this case, the interface that the client knows about is the Subject. Both the Proxy and RealSubject objects implement the Subject interface, but the client may not be able to access the RealSubject without going through the Proxy. It’s quite common that the Proxy would handle the creation of the RealSubject object, but it will at least have a reference to it so that it can pass messages along.

Let’s take a look at this in action with a sequence diagram.

As you can see it’s quite simple – the Proxy is providing a barrier between the client and the real implementation.

There are many different flavours of Proxy, depending on it’s purpose. You may have a protection proxy, to control access rights to an object. A virtual proxy handles the case where an object might be expensive to create, and a remote proxy controls access to a remote object.

You’ll have noticed that this is very similar to the Adapter pattern. However, the main difference between bot is that the adapter will expose a different interface to allow interoperability. The Proxy exposes the same interface, but gets in the way to save processing time or memory.

Would I Use This Pattern?

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

  • The object being represented is external to the system.
  • Objects need to be created on demand.
  • Access control for the original object is required
  • Added functionality is required when an object is accessed.

Typically, you’ll want to use a proxy when communication with a third party is an expensive operation, perhaps over a network. The proxy would allow you to hold your data until you are ready to commit, and can limit the amount of times that the communication is called.

The proxy is also useful if you want to decouple actual implementation code from the access to a particular library. Proxy is also useful for access to large files, or graphics. By using a proxy, you can delay loading the resource until you really need the data inside. Without the concept of proxies, an application could be slow, and appear non-responsive.

So How Does It Work In Java?

Let’s continue with the idea of using a proxy for loading images. First, we should create a common interface for the real and proxy implementations to use:

public interface Image
{
  public void displayImage();
}

The RealImage implementation of this interface works as you’d expect:

public class RealImage implements Image
{

   public RealImage(URL url)
   {
      //load up the image
      loadImage(url);
   }

   public void displayImage()
   {
       //display the image
   }

   //a method that only the real image has
  private void loadImage(URL url)
  {
      //do resource intensive operation to load image
  }

}

Now the Proxy implementation can be written, which provides access to the RealImage class. Note that it’s only when we call the displayImage() method that it actually uses the RealImage. Until then, we don’t need the data.

public class ProxyImage implements Image
{
    private URL url; 

    public ProxyImage(URL url)
    {
       this.url = url;
    }

    //this method delegates to the real image
    public void displayImage()
   {
        RealImage real = new RealImage(url);
        real.displayImage();
    }

}

And it’s really as simple as that. As far as the client is concerned, they will just deal with the interface.

Watch Out for the Downsides

Usually this is the stage that I point out the disadvantages to the pattern. Proxy is quite simple, and pragmatic, and it’s one pattern that I can’t think of any downsides for. Perhaps you know of some? If so, please share them in the comments section

Find Out More


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

An Introduction To Cassandra: The Data Model

I’m fairly new to the whole NoSQL game, and one thing I keep hearing is how great Cassandra is. Built by Facebook and open sourced in 2008, Cassandra is probably the most popular NoSQL implementation: “A massively scalable, decentralized, structured data store”. Cassandra takes it’s distribution features from Dynamo and the data model from BigTable.

Before we look at using Cassandra, we first need to understand the data model. For developers new to Cassandra, coming from a relational database background,  the data model can be a bit confusing. Here’s a summary of how the Cassandra data model is composed:

Column

A Column is the most basic element in Cassandra: a simple tuple that contains a name, value and timestamp. All values are set by the client. That’s an important consideration for the timestamp,as it means you’ll need clock synchronization.

SuperColumn

A SuperColumn is a column that stores an associative array of columns. You could think of it as similar to a HashMap in Java, with an identifying column (name) that stores a list of columns inside (value). The key difference between a Column and a SuperColumn is that the value of a Column is a string, where the value of a SuperColumn is a map of Columns. Note that SuperColumns have no timestamp, just a name and a value.

ColumnFamily

A ColumnFamily hold a number of Rows, a sorted map that matches column names to column values.  A row is a set of columns, similar to the table concept from relational databases. The column family holds an ordered list of columns which you can reference by column name.

The ColumnFamily can be of two types, Standard or Super. Standard ColumnFamilys contain a map of normal columns,

meanwhile Super ColumnFamily’s contain rows of SuperColumns.

KeySpaces

KeySpaces are the largest container, with an ordered list of ColumnFamilies, similar to a database in RDMS. The KeySpace is normally named after the application.

Multiple KeySpaces reside in clusters, the machines/nodes in a Cassandra instance.

For another summary of the Cassandra data model, check out the (nicely titled) “WTF is a SuperColumn“.

In the next article in this introduction series, we’ll move onto the good stuff: using Cassandra in Java.

Meanwhile, why not check out Cassandra: The Definitive Guide from Amazon.