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.

Making the Good Programmer … Better

One of the hardest questions to answer in our industry surrounds the issue of what qualities differentiate a ‘good’ programmer from the rest? I just read Eran Galperin’s “What makes a good programmer?” post on the subject today, and thought that I would share my list of those essential skills and traits that I would look for in anyone on my team.

Adaptable and Flexible

It’s always been the case that you need flexible developers on your team, but at no other time in the short history of software development  has it been so important. If you’re usually the person that does the UI coding, we’ll want you to dig into the persistence layer. We might even want you to go do some testing, which you’d usually run a mile from. You may have been hired as a Java programmer, but we want you to write our next application in .NET, and maybe it’s best to accept that. It’s the world we live in, and you’ll be all the better for it. Multi-tasking is as important as being an expert in one narrow field. At the time it might not be pleasant, but your CV will impress as your next employer sees what you’re willing to do.

Enthusiastic

Maybe you went to university and studied computer science because you heard that was where the money is. A few years in, maybe it was not as rewarding as you expected, and you start getting disillusioned. A great programmer will lovecoding – maybe not the code their working on right now – but in general you should be someone who enjoys building something to solve a problem for someone. When you get a chance to have a cup of coffee at the desk you’ll be going to sites like JavaLobby, and finding how to improve. When you hear about Google’s latest move, or the newest web framework that everyone’s talking about you’re interested. After all, why wouldn’t you be – any ripples in the software development and IT landscape are going to reach you eventually.

A Pragmatic Thinker With a Scientific Mind

The Pragmatic Programmer is one of the most important books in the software industry. Not only is it timeless in the way that it doesn’t tie itself down to one language, but it provides a great set of guidelines. Thinking about the consequences of your actions is essential when working in a team, and my favourite metaphor is “No Broken Windows”. Maintain a consistently high standard in all your work – testing, coding and documentation alike – and others are likely to follow your lead. Let that slip however, and things can take a turn for the worse.

The best way to stay fresh, despite what programming language is currently in fashion, is to keep thinking scientifically. Any problem can be broken down and all languages have a similar set of a characteristics. While this may be natural to some and not to others, the main thing to do is to keep questioning yourself. Can you write this piece of code better? Could I present this information in a more structured way? Mind you, the answer is almost always yes, so use pragmatism to find a reasonable end to this questioning!

Well Organised

When I started programming I would just dive right into my latest task. And that was fine back then, as I was just beginning to get assigned tasks. A few months later, I went to a talk on time-keeping, and learnt a lot that I still utilise today. A good programmer will be well organised, perhaps sitting down at the end of every day to list out the tasks for tomorrow. If someone needs something else done, at least I can refer to this list and see where I can fit it in, or what else will get affected. A useful tool for this is Mylyn, a task based Eclipse plugin.

It pays to be organised on the code and documentation side of things too. An organised approach to packaging, class and variable naming and design, makes everything much easier to follow for others on your team, and for you when you look back at something after a few months.

Reasonable and Approachable

The majority of us work in team environments, so we have to possess people skills. All the great programmers who have respect are those who are approachable. You need to make time for those who feel they need your help, whether that’s a developer with a code problem or a project manager wondering about your estimates. Along with these skills, you should endeavour to be clear in all your communications – the worst thing that can happen after any meeting is that all parties walk out more confused than before.

Being reasonable can’t be underestimated. No matter what your position in the organisation, some negotiation will always be required. Maybe something can’t be done that way you know is right, but in the interests of moving forward, it’s good to be able to find some half-way point, rather than being too head strong.

Takes Chances

You can’t assume that someone else will tell you what the right thing to do is, and when. Maybe you need to move to the latest version of a framework even if you’re close to a release -especially if you feel there’s some benefit there. If you’re enthusiastic about your job, then you’ve probably been keeping up to date with what’s available. And if you’re flexible, you won’t mind sacrificing part of your lunchtime, or your spare time at home, to prototype and see if it works. Every chance has it’s costs, but all need some investigation rather than charging in blindly – be prepared to take that time.

Taking chances applies to your career too. Maybe this new startup is worth joining? Maybe you’re just comfortable in your job right now and you need to challenge yourself. You’ll notice there’s a common theme in any success story – the chance was worth taking, and the chances that were wrong calls help you learn.

Takes Pride In Their Profession

If there’s one point that you can take away and implement from this article it’s this one. Take pride in what you do.  Everything else falls into place, and you will become a great programmer if you take this advice. It’s a lesson learned from all professions – the people we regard as great are those who feel that their industry is the most important, the ones that want to believe that the world needs great programmers.

It’s difficult to do if you don’t love programming, but it’s still possible. You’ve to ask why you don’t like your job right now and find ways to address it. If you’re writing tedious code in the day job, maybe joining an open source project will kick off the spark for you again? You can spot developers who take pride in their profession a mile off, from the quality of the code they write, to their enjoyment at being given a difficult task.

This is just my opinion, and it doesn’t hit any of the real technical aspects of a developers job. Are there any other points here that I’ve missed that help produce the Über-programmer? From the great developers that you have known, what would you describe as their outstanding traits?

Effective Teamworking With Eclipse: Highlighting Local Changes

Eclipse can make your life really easy when it comes to working with version control systems. Over the next few articles, I’ll be sharing some of the tips that I’ve picked up while using Eclipse (with CVS).  When you make changes in your local workspace, the default decoration is a  ‘>’ before the change, up to project level.  This is fine, but isn’t particularly obvious when scanning through your workspace.

You can actually make these changes really stand out using some simple changes to your preferences.  You’ll find the preferences on by navigating to Window/Preferences/Team/CVS/Label Decorations

On the Text Decorations tab you can change the default change flags:

On the general tab, you can change the colors and fonts of anything that has changed locally.
First, click through to the Colors & Fonts page.  This part of the preferences dialog allows you to customize the colors that are used.

Now, when you enable font and color decorations, your changes will be much more obvious:

Hopefully you’ll find this as useful as I did. Eclipse is my everyday IDE, but I’m sure that similar settings exist in other Java IDEs. If so, please share how to access those capabilities with a response (or another article).

Effective Teamworking With Eclipse: Change Sets

The last two days I have been looking at various ways that Eclipse assists developers when working with version control systems. First, we talked about highlighting local changes, then we discussed how to automatically synchronize with the version control system. Todays tip deals with Change Sets, which is themost useful feature in Eclipse for seeing real context behind changes in version control.

To view change sets, you can synchronize as normal but by making a few changes to your Synchronize view, everything looks brighter.

First, go to the preferences dialog in the synchronize view and ensure change sets is visible for models:

Next, choose the drop down list on the third button in the view’s toolbar to choose change sets as your view:

 

Once this is chosen you’ll see all changes in the batches that they were committed in. The name of each change set will be whatever the author used as the commit comment, or if they explicitly create their own change set, it will use the change set title.

 

You can create your own change set by clicking on the changes in the synchronize view and choosing Add To> New Change Set.

Of course the neatest way of managing your change sets would be to use Mylyn, but we’ll cover that in another article.

Using the change sets view while synchronizing automatically makes viewing the differences between your local workspace and CVS simple.

Effective Teamworking With Eclipse: Autosync With Version Control

Over the course of your workday, you should find yourself synchronizing with your version control system frequently. After all, you need to see when somebody’s made a change, and the sooner you know, the sooner you can integrate that change locally before committing. Once again, Eclipse has a really easy way to schedule your syncs.

Everything you need is on the Synchronize view (Window/Show View/Team/Synchronize). From there, you can synchronize which ever projects you want.

Click on the synchronize menu (highlighted in red below) and choose Schedule. Here you can set the frequency of the synchronization.

You can also use the Synchronize Preferences dialog to ensure that when you start up Eclipse, that the sync is triggered automatically.

Put this together with yesterday’s tip and you have much better visibility into what’s going on in version control vs your own workspace.
Tomorrows article will add a final piece that makes teamworking with Eclipse much easier.

Reduce Workspace Noise in Eclipse Using Working Sets

Last week I wrotefew articles on how Eclipse can assist when working in team environments. Today, I have another Eclipse related tip – this time to do with how you organise your local workspace. Developers will typically have a number of projects in their workspace at any one time. If you’re working with a plug-in/OSGi system, the number of projects can be huge.

For example, this is one of my workspaces:

So one of the best ways to reduce the workspace noise is to move to working sets. Typically your projects can be grouped into categories, whether that’s functional or feature related. Choosing Working Sets as your package explorer view, you can group your projects into these sets.

And using the Configure Working Sets option, you can even choose which working sets to display at any time.

From this view you can edit working sets to choose what projects to include. You can also right click on a project at any time and using the Assign Working Sets menu option, send it to one (or many) working sets.

By default, any project without a working set appears in the predefined “Other Projects” working set. Another benefit of this new organisation is that you can “Go Into” any working set (second option in the right click of a working set) to drill down into that working set only:

The new project/import project wizards even allow you to assign the new addition to your workspace to a working set immediately.

It’s all pretty simple, but when I first found this feature it really helped me clear up how I worked. Hopefully it’s useful to you too.

Customizing Eclipse: Setting Up Shortcuts

If you’re using Eclipse as your IDE every day, you’ve probably got certain tasks that you do regularly such as getting projects from version control or writing unit tests, as well as normal coding tasks. This tip shows how you can customize what shows up on your File/New menu for a certain perspective. Some of the commands that you use might be buried under the File/New/Other.. menu. This brings them up a level.

To do this, go to Customize Perspective from the Window menu in Eclipse, while in the perspective where you want the changes to apply.

Here, you will see a number of options that you can add to the New menu. Note that you can also customize shortcuts for the Show View and Open Perspective menus from here.

Just select the items that you want to appear. In the above example, I’ve included the JUnit shortcuts.

Now when I use the File/New menu, these options will be easily accessible:

It’s a pretty simple thing to do, but it might save you a little bit of time.

Deadlines Without Downtime: The Curse of Software Development

A common observation of the software development industry is that it’s immature. And that’s true when compared with more established professions related to construction or medicine. I’ve been thinking that this may be due, in no small way, to the way software developers are treated, which Neil McAllister outlines in his article Developer Burnout: Time To End The Disposable Geek Mentality.

Neil captures the core of the issue in the following paragraph:

Long work hours, missed vacation and sick time, and lack of recognition and advancement are endemic in the software development industry. For all the talk of a “knowledge economy,” some of the smartest and most highly specialized members of the workforce are often treated like disposable labor, easily replaced by newer, cheaper recruits. The result, predictably, is burnout, where the most seasoned team members leave the organization for greener pastures — and or vacate the field completely.

Every sofware developer with a year or two’s experience has served their fair share of crunch time. There’s always something else that needs to be done, deadlines are a constant squeeze and the result is a worn out workforce. And what’s next once the deadline is reached? More of the same.

Sure, managers can do stuff to help out here by allowing key developers to take some time out from the critical path. But usually, the key people are the ones that are always busy. Does taking an agile approach improves things? Yes, but the same demands on the software developer persist.

The thing is, I’m not sure why this is the case, or what could change things. Perhaps software development isn’t looked at as the highly skilled profession that it really is? I know, unlike doctors, we’re not saving lives (for the most of us at least), but with IT at the center of everything, surely developers should be more valued?

Maybe software development has become too cheap – everyone wants to save money, so why pay $100K for a developer if you can get one for $50K? It’s not all about the money, but salary is a big issue for software developers, the same as everyone else. If you can give a developer a salary that means they don’t need to worry about other things, such as how to pay this bill, maybe you improve productivity and the value you get from the developer. The following presentation, from Dan Park, gives some great insights into what works for motivation:

Maybe I’m wrong, but the broad consensus seems to suggest that software developers aren’t treated as well as they should be. Have you got any horror stories that support this claim?

 

Have You Found Your Project In Technical Debt?

I’ve been reading a lot about technical debt recently where people alternate between voluntary technical debt or inadvertant debt. Without doubt, every project has some level of debt, but the important thing is how much do you have, and when do you plan on paying it off.

Martin Fowler says

“Technical Debt should be reserved for cases when people have made a considered decision to adopt a design strategy that isn’t sustainable in the longer term, but yields a short term benefit, such as making a release. The point is that the debt yields value sooner, but needs to be paid off as soon as possible.”

Technical debt is an excellent way for an architect or developer to communicate the cost that a particular decision or implementation made in the short term will affect the project in the longer term.

While in words this works fine, I wonder if there is some type of formula that we can apply to illustrate and track the debt of a project. For each item in the project that causes some debt, it needs to have interest (the cost of not addressing it) and principle (the cost of refactoring the issue to make it work).
While principle could be the number of man days to fix it, I’m stuck with how to express the interest. And how do you work out how much technical debt a project can actually afford. I’m interested to hear if any of you have used the technical debt metaphor in your projects effectively?

There are different types of technical debt, which Martin Fowler describes very neatly in his quadrant diagram:

Reckless and Deliberate

The cost of racing making the deadline at all costs. Once it runs it’s ok right?

Reckless and Inadvertant

Creating a mess without noticing that they’ve done so. Without bringing in any design patterns or real knowledge/experience, debt it going to happen, without the team realising how much of a mess they’ve created.

Prudent but Inadvertant

“If I was starting again, I’d do it differently”. While things were done to the best of the teams ability, we find that there will be a better way.

Prudent and Deliberate

Voluntary debt. The team knows that it’s not quite right, but it’s better to ship and accept the technical debt that will arise because of this.