Why development is still hard in 2006

Life has become considerably easier for developers over the years, particularly with the advent
of managed code (or whatever the equivalent terminology is for Java). Memory usage is something
which one only needs to be aware of rather than constantly being "in your face" in the way it
tends to be in C. However, that doesn't mean that all is rosy, or that we can solely concentrate
on actual business problems. I thought it might be worth a quick run-down of the problems I tend
to find getting the way of more interesting work. In every case things have become a lot simpler
than they were a while ago, and in many cases there are promising new technologies or research
efforts underway to improve the situation further. To be honest, I doubt that any of those improvements
will be enough to remove the relevant item from the list. I expect that if I come back in five years
or so, the list may well be largely the same. So, have I missed any "biggies"? Am I shockingly
stupid for regarding any of these as "hard"? I haven't included user interface design in here,
partly because I have so little experience of it. We seem to keep changing our minds as an industry
about what's "good", and we still seem to keep coming up with UIs with fundamental problems like
not being properly resizable, so I guess we haven't cracked it yet – but I don't think I can
give much insight into the actual problems. Anyway, on to the list…

Installation and updates

Installation is one of those things which tends to get forgotten until near the end of a
development cycle – or at least, it's rare to get it right until you're about to ship. To some
extent, this is due to the fact that it relies on knowing exactly what will need to be installed.
In an ideal world, installation should be very simple in terms of being totally transactional,
so that if anything goes wrong it can be rolled back reliably. If you're just adding files to
the local file system, that's not too far from reality – but for many types of installation there's
a lot more involved. What if you need to install a new database schema, and the database goes down
after you've done that part of the installation but haven't yet finished the other parts? What if
installing the application requires registering on a remote server? Basically, as soon as anything
other than the local box is needed, it's hard to absolutely guarantee a clean rollback. Installation
is often given to junior engineers and regarded as a less prestigious part of the project to work on,
but it's absolutely crucial in terms of customer satisfaction and system stability.

Updates can be even worse – you may need to repair a "broken" system, maintain the customer's
configuration from the previous installation, notice any "customisations" they have made to the
previous installation, possibly upgrade from multiple versions with one installer, etc. Rollback
of an unsuccessful upgrade is even trickier than normal installation, as you'd ideally want to
roll back to the previous system state – an upgrade almost never involves just adding files, as you
usually want to replace previous components.

Finally, installation can be a very platform-specific area to work in. Even if you're only
installing on Windows, there are "gotchas" for each edition – and then you need to potentially check
that the right service packs have been installed, etc. When you come to cross-platform installation,
life is even worse. Checking that any dependencies are installed (and in the way you expect them to be),
making your application available in the appropriate way for that system, integrating with whatever
installer services are the norm – it's enough to drive a person crazy.

Versioning

Tied in with installation is versioning across communicating systems. I've only recently had to deal
with this – it's certainly not something that all developers are likely to need. When you do
need it, however, it's a pain. Suppose version 2 of your application needs to be able to talk with
version 1 and vice versa. Undoubtedly v2 will have features that v1 doesn't support, and it
may implement the v1 features in a slightly different way. The details of what is communicated in
what situation are tricky to get right. This is one of those problems which isn't too hard to handle
for any particular small case, but the difficulty lies in being rigorous in the definition of what
you're allowed to do without a component (or whatever you use as your unit of versioning) needing to
really change version. You may be able to add some data, using a default when it's not provided, but
not change a method signature, for example. Likewise, depending on what technology you're using
for the communication, you may need to lay down rules about exactly how data is sent between the systems.
Once those rules have been precisely defined, you then need to be utterly meticulous about sticking to them.
Following rules is tedious, and all developers can be forgetful on occasion.

Oh, and then there's the testing, of course. Do you support a connected system which includes two
installations of v1, one installation of v2, and one installation of v3? What if for v3 you've decided
to drop some of the v1 functionality? When writing v1, you need to be aware of future possibilities
so you can handle them cleanly. The principle of YAGNI
is less applicable here than normal, because we can't accurately predict the future. YAGNI is fine when you
can implement a feature later on, but it's less useful when you don't get to force all your customers
to upgrade all their systems. While you don't need to predict everything you'll implement later, you may
well need to build features in now to accommodate changes later on.

Internationalisation

Up-front warning: I'm not an expert on i18n. That's one of the problems – there are very few people who are.
I know what Unicode surrogates are, and I know that very little of my own code handles them properly. I know
a bit about some of the more common encodings available. I know of little gotchas like the capitalised form
of "i" not being "I" in Turkish (having been bitten by that one in a previous job) – that when you consider
some manipulation of text data, you'd better know whether it should be done in the system locale, the user's locale,
the database's locale, a different specific locale, whatever. I know that a UI designed without taking into
account that labels will take up different widths in different languages is likely to fall flat when it's
localised. I know that repeatedly replacing "  " (two spaces) with " " (one space) until you can't find "  " (two spaces) any more can lead to
an infinite loop in .NET, as String.Replace treats zero-width characters differently to
String.IndexOf.

These are just wrinkles I've come up with off the top of my head – I'm sure I could think of plenty more if
I wanted to provide a longer list. All of that is without being in any way an expert. Goodness knows
what bizarre stories someone genuinely knowledgeable could tell. Now, although I'm not an expert, I'm reasonably
intelligent. I don't expect all the other developers on my team to have all the expertise I'm missing. Heck, I
don't expect there are that many projects which have even a single genuine i18n expert. Even if they did,
that expert would have to review virtually all the code of the project: how many classes do you write
which really don't have any text manipulation? It's not just text which ends up in front of a user which
you need to be careful with…

I strongly suspect that almost all applications are broken to a greater or lesser extent when it comes to i18n.
How many validation routines take surrogates into account? How many servers have the same bug which we happened
to find and fix, trying to do a case-insensitive comparison of header names by upper-casing the name in the system
locale? How many systems are going to correctly handle sorting characters in Japanese text, taking the kana into account?
I don't know whether it would be more depressing to think I was just singularly incompetent, or whether it's worse to believe
that everyone else is just as ignorant of these issues as I am.

Date and time handling

I've broken this part of i18n out into its own topic because it's so nasty even if you only have one culture to deal with.
When do you use UTC, and when do you use a local time? How easy is it to get at the local time? When should you use the local
time of the user, and when should you use system times? What about daylight saving times, which can lead to some local date/time
combinations being ambiguous and others being impossible? How do you gracefully cope with the system time changing abruptly?

There are four core problems here, as far as I can see. Firstly, there's working out what to do in any particular
situation. Sometimes the answer is obvious, and we've learned a lot over time about best practices – keeping date/times in
UTC as long as possible, for instance. In other cases the answer is harder to work out, or different users may have different
goals or expectations, leading to no one correct solution.

The second problem – one which is often ignored – is communicating your decisions. Agreeing on some terminology can help,
but everyone needs to be willing to take a bit of time to internalize the "rules". This is the case in many areas of
development, but I've found that date and time handling tends to be particularly tricky, just because unless you're really
precise about what you mean, different people will interpret your words in different ways. The more actors in the system,
the worse it gets: if you're considering the situation where you have a server in Australia administered by someone in London,
with a helpdesk operator in Germany answering a call from someone in France, the chances of everyone agreeing on exactly
when something happened are really slim.

Thirdly, the commonly available libraries are pretty rubbish at the moment. Java allows you to do the right thing, but
because it's taken several goes to get it right, there are deprecated methods everywhere. The decision to make months
0-based makes sense in some ways, but catches pretty much everyone out sooner or later, and can make tests harder to read.
The precise behaviour of calendars in terms of setting/adding/rolling different inter-related fields is fairly precisely
defined, but not easy to understand. There's no simple access to the UTC timezone without magic strings. The use of inheritance
between java.util.Date, java.sql.Date and java.sql.Timestamp can lead to tests
failing unexpectedly. At least you can generally do what you want though, with a bit of work – .NET is far worse in this
respect. In 1.1, there was no way of knowing whether a DateTime was local or UTC; calling ToLocalTime()
repeatedly would keep changing the time by the timezone offset on every call. In .NET 2.0 there's the DateTime.Kind
property which helps, but it's a bit of a sticking plaster. There's still no way (in the framework itself) of getting at the
system's list of timezones. I dare say this will improve over time, but I can't see why it's taken so long to get even this far.
I'm sure there are smart people at Microsoft who know the kind of thing required for writing applications which will be have users
in different timezones to the system itself – why weren't they more involved in designing the API?

Fourthly, there's the real world, where politicians may arbitrarily decide to change daylight savings etc. There has been talk
about changing Britain's timezone to be one hour ahead of where it is now. How would that affect all the software in the world?
How many systems would need to know about the change? How would they all find out about it? It feels to me like the same kind of
scale of change as altering the currency of a country – possibly worse, as there are lots of applications which deal with times
but don't ever need to deal with money.

Resource handling

I said at the start of this article that memory handling wasn't much of an issue now if you're using .NET or Java.
You need to be slightly careful to make sure you don't have orphans due to events, static members etc, and you need
to be aware of what's going on in order to avoid making gross inefficiencies for no reason, but most of the time
you don't need to worry about things. This isn't the case when it comes to other resources, such as file handles,
network connections, etc.

I've read posts by C++ developers who maintain that C++ has effectively solved the situation with
RAII and auto_ptr. I don't
know enough about C++ to say to what extent this is true, but in .NET and Java, without deterministic finalization (for
pretty compelling reasons, in my view) you still need to handle non-memory resources manually. Now, C# provides the very
useful using statement (which I deeply miss when working in Java) to make life easier, but there's still the
manual element of making sure you always use it in the right place. There's still got to be a sense of someone "owning"
the resource, and that object (and only that object) releasing it, and nothing else trying to use the released resource
reference afterwards. A good example of this problem is when creating an image from a stream in .NET. Whenever I use a
stream in .NET, I habitually start wrapping it in a using statement – but if I'm providing the stream to
Image.FromStream, I have to notice in the documentation that I've got to keep the stream open for the lifetime
of the Image. The documentation doesn't make it clear whether or not disposing the image will close the stream
for me. Furthermore, making the transfer of ownership from the calling code to the image atomic is far from straightforward.

This is the area in which I have the most hope for the future. Possibly the successor to .NET will have resource clean-up
all sorted out. I dare say it'll be a long time coming, but I still plan to be developing in 15 years' time. I hope at
that point I can look back and shake my head at the hoops we have to go through today.

Concurrency

Increasingly, developers need to know about threading. Gone are the days where most developers could rely on their
application being the only one running on the box at the time, and it being okay to just make the user wait for a while if
a time-consumering operation was required. Like i18n, I'm not a threading expert. I probably know more about it than
most developers due to investigating it more (I find the whole business fascinating) but that doesn't make me an expert.
I've tried to write about the topic in an accessible way, but there are huge areas I haven't written about, simply
because I don't know about them. Every so often I'll come across an
optimisation I wouldn't have thought would be valid
which could call into question code I thought was reasonably safe. So, to start with, there's a lot to know.

Then there's a lot of care to be taken. In some ways, avoiding deadlocks is straightforward: keep locks for as short a time as
possible to avoid contention, and if you ever take out more than one lock, make sure that the code paths that will take
out those multiple locks always acquire them in the same order. The reality of implementing that strategy is much harder than it sounds,
in my experience – certainly when the system gets large.

Then there's the technology side of things – the facilities provided to us by the platform we're working on. These have
improved by leaps and bounds over the years, and things like the
CCR sound like they'll make life easier.
All I'd say is that we're not there yet. While every call from a background thread to a UI thread needs some manual coordination,
there's still work to do. One problem is that to get things right, you tend to need to know a certain amount of what's going
on under the covers: while I expect life to get easier for developers, I think they'll still to understand a bit about
tricky things like memory models and the strange optimisations that are permissible.

Error handling

Exceptions are lovely. I generally agree with Joel Spolsky, but I completely disagree with his
view on exceptions. That's not to say he doesn't make some
good points, but I consider his solutions to the problems of exceptions to be worse than the problems themselves. Returning
error codes has proved to be a dangerous way of working – it's far too easy to forget to check the code. The equivalent with
exceptions is catching an exception and then ignoring it – and that happens in real code, far more often than it should,
but at least it requires actual code to do the wrong thing.

So, why is error handling still in my list? Because we haven't become good at using exceptions yet. We still find
it tricky at times to know the right point to catch an exception, and in what rare circumstances it's right to catch
everything. Also, there's more to error handling than just exception handling. How forgiving should we make our
systems? How do we report errors to the user? How do we give users error information which is precise enough for our support
team but which doesn't scare the user to death? Oh, and how do we educate developers not to catch exceptions and ignore them
without having a really good reason?

Part of this may be technological. Java tried an experiment with checked exceptions, and although I was a fan of them
for a few years, I've changed my mind over time. I think the experiment was worth trying, and there were some benefits
that ought to be captured by the Next Big Thing, but the overall effect wasn't all it could be. I'm not smart enough to
come up with the Next Big Thing myself, but I'm hoping it will improve reliability without giving the developer more grief.

API creep

If the previous topic was a bit ropey, this one barely made it on the list at all. It should definitely be on a
list, however, and the link is tenuous but just about visible, so it can live here for the moment.

I've commented before how CVs these days have shopping lists of technologies on them. Regardless of how accurate those
CVs are, the technologies themselves certainly exist and are being used by someone, somewhere. Just take one topic: XML,
for example. How many XML APIs/technologies do you know? How many more do you know of even if you haven't used them? Here's
a list off the top of my head, without reference to the net:

DOM, SAX, JDOM, dom4j, Xerces, Xalan, STaX, MarkupBuilder (and related),
XPath, XQuery, XSLT, xpp3, Jaxen, JAXP, XmlReader (and related), Xstream.

Yikes! Just keeping up with all the XML APIs would be a full-time job, and that's just XML! Trying to stay on top of
the standard libraries of both .NET and Java is equally tricky. How is anyone meant to cope? My personal answer is to focus on the
technology I need to solve the problem at hand, but to try to keep an ear to the ground to at least have a passing awareness
of interesting things I may want to use in the future. It's impossible to gauge how successful I am at that, but I know that
it's a time-consuming business, and I see no sign of the software industry slowing down. Don't think I'm not grateful for
all the work that these technologies save me – I'm just recognising that the variety available comes with a penalty.

Conclusion

Here in 2006, life is still tricky in software development. From a career point of view, that's a good thing – I'm pretty good
at what I do, and if everything became trivial, I guess I wouldn't have as much employment value. On the other hand,
some of these problems have been with us a long time and we're making lamentably slow progress towards making them
no-brainers. Someone remind me to come back to this list in 2011…

Opening up the .NET framework source code

For a long time, I've believed that Microsoft should open up the source code to the .NET framework
– at the very least, the managed parts of the standard library, and preferrably most/all of the
unmanaged part of the framework and even the CLR itself. As Sun gradually works its way to
making Java more fully open source, MS should at least make the source available to the same
extent that Sun has made the Java standard libraries available for years. This is not the same
as making the framework an Open Source project, of course.

Reasons to open up the framework

Exploring implementation details

MSDN is generally very good, but every so often it's either ambiguous or just plain wrong.
Sometimes it makes sense for documentation to be ambiguous – it allows behavioural changes
later on – but sometimes you really need to know what the behaviour will be, even if you're
only guaranteed that behaviour for the current version. (At that point, a request for the
behaviour to be more fully specified is a good move.) Having the source code available
makes this exploration possible – as well as enabling those who answer questions about the framework
to give answers based on more than just experimentation.

Debugging

Sometimes, it's just not clear why code is behaving the way it does. Much as I dislike having
to use a debugger, it's unavoidable at times. That's okay so long as you can actually debug
all the code which is in question. If a framework method is behaving in an unexpected manner,
it can be very hard to work out why. Being able to debug with symbols available has often been
helpful to me in Java, and I've often wished I had the same ability in .NET.

Understanding and reporting bugs in the framework

The .NET framework isn't perfect. Every so often, there are bugs, and that's completely
understandable. It would be frankly remarkable if the framework didn't have any bugs.
However, even when you think you've found a bug, it can be an awful lot easier to demonstrate
and reproduce in a guaranteed fashion if you've got the source code available. That can make it
easier for Microsoft to fix it, and it's also easier to work round it for the time being.

People are reading source anyway with Reflector

Lutz Roeder's Reflector is fantastic. It's
a disassembler/decompiler for .NET code. Admittedly it's the kind of tool that scares people
into obfuscating their code,
when it's usually an unnecessary hurdle which makes life harder for developers but not
that much harder for pirates. However, it means people can dive into the framework when they
need to. They can't debug into it, or read comments, or see local variable names – but they
can check out what's going on in a fashion. If MS cares about this sufficiently little that
they don't obfuscate the code, why not make it available in a more developer-friendly manner?

That leads me to what I suspect may be the other side of the argument…

Reasons not to open up the framework – and counter-arguments to them

Commercially sensitive code

It's possible that Microsoft have some really clever code in the framework. I'm sure there's
quite a lot of clever code there, actually, and I'm sure it took more man-hours to write
than I really want to think about – but I doubt that there's much in there which is
sufficiently novel that it would give competitors much advantage. If there is any
code in there which is so secretly wonderful it mustn't be discovered, it can still be read
with Reflector – unless it's been selectively obfuscated. If it can be selectively obfuscated,
no doubt it could be selectively left out of any source code distribution. I suppose that would
be painting a bit of a target, but it wouldn't be hard to check the class library for obfuscation.

Security-sensitive code

Maybe there are bits of the framework which really aren't as secure as they should be, and MS
is worried that if people can see how everything works, they'll work out how to crack it, too.
That's security through obscurity – and it's generally not a good idea. I really hope this isn't
the reason. (I'm kinda hoping this blog is being read by a few Softies who might be able to
explain what the real reason is.)

Unprofessional or negative comments

Developers can occasionally have a bit of a giggle in comments – and other comments may well
point out bits of code which need further work. Both of these could raise a few eyebrows in
manager-land, even if most developers would understand it's a normal part of life. There are
ways round this though – strip comments for the first "drop" of source code, then gradually
put them back in, for example. Leaving the useful comments in would be lovely, of course, but
code without comments is better than no code at all.

Performance/download/management worries

Downloading the source would take a long time. Downloading the symbols may take a long time.
You'd probably need a different copy of the binaries with debugging enabled (I can't remember
the details off-hand). You'd need to be able to pick whether or not you wanted to use the source
when launching a debugging session. All of these are things which would cost MS some time
to get right – but they're not that strapped for resources.

General paranoia

This sounds like the most probable reason in my view. Opening up source code makes managers
(and those above) nervous. Heck, it would probably make me nervous too. There are natural
fears about letting people see the details of code when they've been able to treat it as
a black box for a while. However, the benefits to developers are pretty huge in my opinion.
It's worth facing that fear and examining the issue carefully. It would probably be instructive
to see what Sun has lost through making the source code for most of their Java implementation available.

Conclusion

I'm not expecting to see MS open up the framework code any time soon. I think it's a pity,
but life's full of disappointments. Maybe people inside Microsoft are lobbying for it too – I
really don't know. Maybe I'm the only Java/C# developer who really misses having the code available
when working on .NET. Maybe you'll let me know in comments :)

An alternative CV strategy

This is my second attempt at writing this. Memo to self: after hitting the Post button, make sure the post has actually been published before navigating away from the page…

I’ve been reading a fair number of CVs recently, and I’ve been struck by just how much experience everyone seems to have. At least, everyone claims to have a breadth of experience that I just can’t match. I haven’t counted, but I suspect most of the CVs I’ve been looking at have listed over 100 technologies. In light of this, I’ve been considering how I’ll market myself when I’m next interested in getting a job.

There are a few things in my favour which most candidates don’t have, mostly in terms of community – MVP awards, book reviewing, web articles, this blog, newsgroup posts, open source contributions etc – but I don’t know how much attention prospective employers really pay to that kind of thing. What I find frustrating is the way that traditional CVs don’t really convey any of what I find important – either as a potentially employee or as someone involved (to whatever extent) in the hiring process. I have begun to wonder whether a list of values would do me any favours:

  • I prefer working code over perfect UML
  • I prefer whiteboards over Visio
  • I prefer code which can easily be read over code which runs 5% faster but no-one else understands
  • I prefer code reviews which force me to change my design over reviews which stroke my ego
  • I prefer being laughed at due to my trousers over being disrespected for being sloppy
  • I prefer going home at 5 to sleep on a problem over staying at the office until midnight and then being useless the next day
  • I prefer carrots over sticks
  • I prefer progress over process
  • I prefer keen developers with much to learn over experienced developers who feel they have nothing to learn
  • I prefer close collaboration over the heroic coder mentality
  • I prefer solving problems people are having in the real world over providing marketing with a new toy to show off

Maybe that doesn’t go far enough towards selling me though. How about some more direct statements?

  • I write clean code in a timely manner
  • I test my work and refactor mercilessly
  • I don’t assume my code is perfect
  • I love to learn new techniques and technologies
  • I love to teach, and can explain things clearly
  • I pick up new things quickly
  • I have an affinity for code which lets me solve issues quickly
  • I bring passion to whatever I do

If someone presented me with a CV based on the above lists, I’d be interested. Yes, I’d probably check that the candidate had worked in some sort of similar area before, but frankly if you take a bright person and ask them to learn Java or C#, it’s not going to take them that long to do it. Learning design principles takes longer (I’ll let you know if I ever think I’ve finished!) but with good mentoring, it’s not a problem.

CVs can’t be trusted. People can write pretty much anything on them. However, they’re making a choice about what image to present to the world – and that choice itself makes a statement. I want to work with smart people who love what they do. I want to see a spark in their eyes when they tell me what they’ve been up to. At an interview, I want them to be so busy getting me enthusiastic about what they’ve been looking at that I don’t have time for the standard questions.

You may well consider the lists above to be unprofessional to an extent. I agree – but I’m not sure whether it’s a problem. I enjoy my work immensely – so much so that I hardly think of it as work for a lot of the time. That’s not to say it’s not important to do a professional job – but there’s often not much of a gap between what I’m interested in for fun and what I earn money doing.

I suspect if I gave an unconventional CV to an agency they’d either demand a rewrite or they’d change it themselves. Maybe they’d be right to do so – maybe managers aren’t really keen on this sort of thing. What do you think? Comments are always welcome on my blog, but I’m particularly keen on feedback this time, as it could have a real bearing on what I do when I’m next in the job market.

Elegant comparisons with the null coalescing operator

A while ago I commented on how I’d like a return? statement, which
only returned if the return value was non-null. The purpose of this was to remove
the irritation of implementing Equals and IComparable.CompareTo
on classes with several properties. For an example of the kind of thing I mean,
consider an Address class with properties Country,
State, City, ZipCode and HouseNumber.
(Apologies to readers who aren’t American – while I feel a traitor to my country for
using state instead of county and zip code instead of post code, I’m guessing there are
more readers from the US than from elsewhere.)

This Address class needs (for whatever reason) to be comparable to itself,
comparing the properties in the order described above, in normal string comparison order.
Let’s see how annoying that is without doing anything clever. (I haven’t included
any property implementations or constructors, but I’m sure you can all guess what they’d
look like. Similarly, I haven’t overridden object.Equals or object.Hashcode,
but the implementations are trivial.)

using System;

public sealed class Address : IComparable<Address>
{
    string country;
    string state;
    string city;
    string zipCode;
    int houseNumber;
    
    public int CompareTo(Address other)
    {
        if (other==null)
        {
            return 1;
        }
        int ret = country.CompareTo(other.country);
        if (ret != 0)
        {
            return ret;
        }
        ret = state.CompareTo(other.state);
        if (ret != 0)
        {
            return ret;
        }
        ret = city.CompareTo(other.city);
        if (ret != 0)
        {
            return ret;
        }
        ret = zipCode.CompareTo(other.zipCode);
        if (ret != 0)
        {
            return ret;
        }
        return houseNumber.CompareTo(other.houseNumber);
    }
}

That’s ignoring the possibility of any of the properties being null. If
we want to include that possibility, it’s worth having a static helper method which
copes with nulls, along the lines of object.Equals(object, object).

Now, if we don’t care about doing more comparisons than we really want to and
potentially creating an array each time, it wouldn’t be hard to implement a series
of overloaded methods along the lines of:

public static int ReturnFirstNonZeroElement(int first,
                                            int second,
                                            int third)
{
    return first != 0 ? first :
           second != 0 ? second :
           third;
}

(The array part would be when you implement ReturnFirstNonZeroElement(params int[] elements)
after you’d got enough overloads to get bored.)

That still ends up being a lot of code though, and it’s doing unnecessary comparisons.
I’m not keen on micro-optimisation, of course, but it’s the inelegance of it that
bothers me. It feels like there must be a way of doing it nicely. With
C# 2.0 and the null coalescing operator, we do. (At this point I’m reminded that
the irritation actually came when writing Java, which of course doesn’t have anything
similar. Grr.) For those who are unaware of the null coalescing operator (and it’s one of the
least well publicised new features in C# 2.0) see
my brief coverage of it.
Now consider the following helper method:

public static int? CompareFirstPass<T>(IComparable<T> first, T second) 
    where T : IComparable<T>
{
    if (first==null)
    {
        return -1;
    }
    // Assume CompareTo deals with second being null correctly
    int comparison = first.CompareTo(second);
    return comparison==0 ? (int?)null : comparison;
}

In short, this returns the result of the comparison if it’s non-zero, or null otherwise.
Now, with the null coalescing operator, this allows the Address class implementation
of CompareTo to be rewritten as:

public int CompareTo(Address other)
{        
    return other==null ? 1 :
           Helper.CompareFirstPass(country, other.country) ??
           Helper.CompareFirstPass(state, other.state) ??
           Helper.CompareFirstPass(city, other.city) ??
           Helper.CompareFirstPass(zipCode, other.zipCode) ??
           houseNumber.CompareTo(other.houseNumber);
}

It’s short, simple and efficient. Now, doesn’t that make you feel better? :)

Broken windows and unit testing

There’s quite possibly only one person in the world reading this blog who doesn’t think
it’s got anything to do with Vista. The windows in the title have nothing to do with
Microsoft, and I’m making no assertions whatsoever about how much unit testing gets done
there.

The one person who understands the title without reading the article is Stuart,
who lent me The Tipping Point
before callously leaving for ThoughtWorks,
a move which has signficantly reduced my fun at work, with the slight compensation
that my fashionable stripy linen trousers don’t get mocked quite as much. The Tipping
Point is a marvellous book, particularly relevant for anyone interested in cultural
change and how to bring it about. I’m not going to go into too much detail about the
main premises of the book, but there are two examples which are fascinating in and
of themselves and show a possible path for anyone battling with introducing
agile development practices (and unit testing in particular) into an existing
environment and codebase.

The first example is of a very straightforward study: look at unused buildings, and
how the number of broken windows varies over time, depending on what is done with
them. It turns out that a building with no broken windows stays “pristine” for a
long time, but that when just a few windows have been broken, many more are likely
to be broken in a short space of time, as if the actions of the initial vandals
give permission to other people to break more windows.

The second example is of subway trains in New York, and how an appalling level
of graffiti on them in the 80s was vastly reduced in the 90s. Rather than trying
to tackle the whole problem in one go by throwing vast resources at the system,
or by making all the trains moderately clean, just a few trains were selected
to start with. Once they had been cleaned up, they were never allowed to run
if they had graffiti on them. Furthermore, the train operators noticed a pattern
in terms of how long it would take the “artists” in question to apply the graffiti,
and they waited until three nights’ work had been put in before cleaning the
paint off. Having transformed one set of trains, those trains were easier to keep
clean due to the “broken windows” effect above and the demotivating aspects of
the cleaning. It was then possible to move onto the next set, get them clean
and “stable”, then move on again.

I’m sure my readership (pretentious, eh?) is bright enough to see where this is
leading in terms of unit testing, but this would be a fairly pointless post if I
stopped there. Here are some guidelines I’ve found to be helpful in “test infecting” code,
encouraging good practice from those who might otherwise be sloppy (including myself)
and keeping code clean once it’s been straightened out in the first place. None of
them are original, but I believe the examples from The Tipping Point cast them in
a slightly different light.

Test what you work with

If you need to make a change in legacy code (i.e. code without tests), write
tests for the existing functionality first. You don’t need to test all of it,
but do your best to test any code near the points you’ll be changing. If you
can’t test what’s already there because it’s a
Big Ball of Mud
then refactor it very carefully until you can test it. Don’t start
adding the features you need until you’ve put the tests in for the refactored
functionality, however tempting it may be.

Anyone who later comes to work on the code should be aware that there are
unit tests around it, and they’re much more likely to add their own for whatever
they’re doing than they would be if they were having to put it under test
for the first time themselves.

Refactor aggressively

Once code is under test, even the nastiest messes can gradually get under
control, usually. If that weren’t the case, refactoring wouldn’t be much use,
as we tend to write terrible code when we first try. (At least, I do. I haven’t
seen much evidence of developers whose sense of design is so natural that
elegance flows from their fingers straight into the computer without at
least a certain amount of faffing. Even if they got it right for the current
situation, the solution isn’t likely to look nearly as elegant in a month’s
time when the requirements have changed.)

If people have to modify code which is hard to work with, they’ll tend to
add just enough code to do what they want, holding their nose while they do it.
That’s likely to just add to the problem in the long run. If you’ve refactored
to a sane design to start with, contributing new elegant code (after a couple
of attempts) is not too daunting a task.

Don’t tinker with no purpose

This almost goes against the point above, but not quite. If you don’t need
to work in an area, it’s not worth tinkering with it. Unless someone (preferrably
you) will actually benefit from the refactoring, you’re only likely to provoke
negative feelings from colleagues if you start messing around. I had a situation
like this recently, where I could see a redundant class. It would have taken maybe
half an hour to remove it, and the change would have been very safe. However,
I wasn’t really using the class directly. Not performing the refactoring didn’t
hurt the testing or implementation of the classes I was actually changing, nor was it
likely to do so in the short term. I was quite ready to start tinkering anyway,
until a colleague pointed out the futility of it. Instead, I added a comment suggesting
that the class could go away, so that whoever really does end up in that area
next at least has something to think about right from the start. This is as much
about community as any technical merit – instead of giving the impression that
anything I had my own personal “not invented here” syndrome (and not enough “real work”
to do), the comment will hopefully provoke further thought into the design decisions
involved, which may affect not just that area of code but others that colleagues work
on. Good-will and respect from colleagues can be hard won and easily lost, especially
if you’re as arrogant as I can sometimes be.

Don’t value consistency too highly

The other day I was working on some code which was basically using the wrong naming
convention – the C# convention in Java code. No harm was being done, except everything
looked a bit odd in the Java context. Now, in order to refactor some other code towards
proper encapsulation, I needed to add a method in the class with the badly named methods.
Initially, I decided to be consistent with the rest of the class. I was roundly (and
deservedly) told off by the code reviewer (so much for the idea of me being her mentor –
learning is pretty much always a two-way street). As she pointed out, if I added another
unconventional name, there’d be even less motivation for anyone else to get things right in
the future. Instead of being a tiny part of the solution, I’d be adding to the problem.
Now, if anyone works in that class, I hope they’ll notice the inconsistency and be encouraged
to add any extra methods with the right convention. If they’re changing the use of an existing
method, perhaps they’ll rename it to the right convention. In this way, the problem can gradually
get smaller until someone can bite the bullet and make it all consistent with the correct
convention. In this case, the broken windows story is almost reversed – it’s as if I’ve
broken a window by going against the convention of the class, hoping that all the rest of
the windows will be broken over time too.

This was a tough one for me, because I’ve always been of the view that consistency
of convention is usually more important than the merit of the convention. The key here is that
the class in question was inconsistent already – with the rest of the codebase. It was only
consistent in a very localised way. It took me longer to understand that than it should have
done – thanks Emma!

Conclusion

Predicting and modifying human behaviour is an important part of software engineering
which is often overlooked. It goes beyond the normal “office politics” of jockeying for
position – a lot of this is just as valid when working solo on personal code. Part of
it is a matter of making the right thing to do the easy thing to do, too. If
we can persuade people that it’s easier to write code test-first, they’ll tend to
do it. Other parts involve making people feel bad when they’re being sloppy – which
follows naturally from working hard to get a particular piece of code absolutely clean just
for one moment in time.

With the right consideration for how future developers may be affected by changes we make
today – not just in terms of functionality or even design, but in attitude, we can
help to build a brighter future for our codebases.

The 7 Deadly Sins of Software Development


Introduction

Recently, Eric Gunnerson made a post
in his blog with the idea of “the seven deadly sins of
programmers”. Eric is posting his ideas for such a list one at a time, periodically. He invited others to write
their own lists, however, and it was such an intriguing idea that I couldn’t resist. The list is in descending
order of importance (I figure not everyone will make it to the bottom of this post) but the order is fairly
arbitrary anyway. Hopefully none of this will be a surprise to most of my readership, but it’s nice to write
as a sort of manifesto anyway. I’ve included a “personal guilt rating” out of 10 for each of these sins. I’m
very willing to change these in the light of feedback from those with experience of working with me :)

#1 – Overengineering (in complexity and/or performance)

Personal guilt rating: historically 8, currently 3

It’s amazing how much people care about performance. They care about the smallest things, even
if there’s not a chance that those things will have a significant impact in reality. A good example
of this is implementing a singleton. I’ve seen
the double-checked lock algorithm (as described on the page, except often broken) repeatedly brought
forward as the best way to go. There’s rarely any mention of the fact that you have to get it just right
(in terms of making the variable volatile or using explicit memory barriers) in order for it to be properly
thread-safe. There’s no way of making it work in Java, so anyone porting code later will end up with a bug
they’re very unlikely to be aware of. Yet people use it over simply locking every time on the grounds of
performance. Now, acquiring an uncontested lock is very, very cheap in .NET. Yes, it’ll be slightly more expensive
on multi-processor boxes, but it’s still mind-bogglingly quick. The time taken to lock, check a variable for nullity
and then unlock is unlikely to cause a significant issue in almost any real world application. There may be a very,
very few where it would become a problem – but developers of those applications can profile and change the code
when they’ve proved that it’s a problem. Until that time, using double-checked locking just adds complexity
for no tangible benefit.

That’s just a single example. People are always asking performance questions on the newsgroups which just won’t
make a difference. For example, if you have a string reference in an Object expression, is it faster
to cast it to String or to call the toString method? Now, don’t get me wrong – I find
it very interesting to investigate this kind of thing, but it’s only as a matter of interest – not because I think
it should affect what code should be written. Whatever the result, the simplest code which achieves
the result in the most readable fashion is the best code until performance has proved to be an issue.

I should stress that this doesn’t extend to being stupid about performance. If I’m going to concatenate an unknown
number of strings together, I’ll use StringBuilder
of course – that’s what it’s designed for, and I’ve seen that it can make a huge difference in real world situations.
That’s the key though – it’s evidence based optimisation. In this case it’s general past evidence, whereas for many other
situations I’d use application-specific evidence, applying an optimisation which may make the code harder to read only
when I’ve proved that the particular application in question is suffering to a significant extent.

The other side of this issue is complexity in terms of what the solution can achieve. These days,
I mostly code for testability, knowing that if I can test that my code does what it wants to, chances are
it’ll be flexible enough to meet my needs without being overly complicated. I look for complexity all over the place,
particularly in terms of trying to anticipate a complicated requirement without knowing that the requirement will
actually be used. For instance, if I’m writing some kind of collection (not that that happens often), I won’t add sorting capabilities
until I know they’re needed. It just creates more work if you write unnecessary code. Of course, when writing libraries for
public consumption, things become much trickier – you basically can’t tell how a library will be used ahead of time,
so you may well end up adding features which are rarely used. The closer the communication between the code and its clients,
the better. (This is also relevant in terms of performance. One area I did spend time optimising was the
enhanced locking capabilities part of my miscellaneous
utility library. Locking is cheap, so any replacement for “standard” locking should also be cheap, otherwise it discourages
its own use.)

When I look at a design and see that it’s simple, I’m happy. When I look at implementation and see that it’s simple, I’m happy.
It’s not “clever” to write complicated code. Anyone can write complicated code – particularly if they don’t check that it works.
What takes time is writing simple code which is still powerful.

#2 – Not considering the code’s readership

Personal guilt rating: 4

This is actually closely linked to the first sin, but with a more human face. We know that code is generally in
maintenance for longer than it’s under initial development. We know that companies often (not always, thankfully) put their
“top developers” (however they decide to judge that) onto feature development rather than maintenance. These make it
essential that we consider “the next guy” when writing our code. This doesn’t necessarily mean reams of documentation –
indeed, too much documentation is as bad as too little documentation, as it can make the code harder to read (if it’s
inline code documentation) or be hard to find your way around (if it’s external documents). One project I was working on
decided to extract one document describing data formats from the main system architecture document, and we found that the
extracted document became absolutely crucial to both testers and coders. That document was kept accurate, and was short enough
to be easy to follow. The document from which it was extracted was rarely used.

Of course, the simpler the code, the less documentation is required. Likewise, well-written unit tests can often express the
correct behaviour (and expected use) of a class more succinctly than lots of documentation – as well as being kept accurate
automatically.

There are times when writing good documentation is very difficult indeed. Recently I wrote a class which did exactly the right
thing, and did it in an elegant manner. However, explaining what its purpose was even in person was difficult. Understanding
it from just the documentation would be almost impossible – unless the reader looked at what problem was being solved and worked
through what was required, which would lead fairly naturally to the same kind of solution. I’m not proud of this. I’m proud of the
class itself, but I don’t like finding myself stuck for words.

Sometimes, simple code (in terms of number of characters) is quite complicated. At one point on a project I had to find
whether only a single bit was set in a long. I’m no good at remembering the little tricks involved for this kind of thing,
but I’m aware they exist, and using them can be a lot more reliable than writing bit-twiddling loops to do things in a
long-winded fashion. In this case, we found the appropriate trick on the web, and included a link in the code. Without the link
(or at least a description in a comment) the code would have been effectively incomprehensible to anyone who didn’t recognise the
trick.

Code reviews definitely help readability – when they’re done properly. In some ways, they can be better than pair programming
for this, particularly if the original developer of the code doesn’t try to explain anything to the reviewer. At this point
the reviewer is able to take on the role of the first person who has to maintain the code – if anything isn’t clear just from
what’s available in terms of code and documentation (as opposed to human intervention) then that probably needs a bit of work.
Not verbally explaining what’s happening when you’re the author is incredibly difficult to do, and I’m very bad at it. It adds
time to the review, and when you’re under a lot of pressure (and who isn’t?) it can be very frustrating to watch someone
painstakingly understanding your code line by line. This is not to say that code reviews shouldn’t be the source of discussion
as well, of course – when I’m working with people I respect, I rarely come through a review without some changes to my code,
and the reverse is true too. After all, what are the chances that anyone gets something absolutely right to start with?

#3 – Assuming your code works

Personal guilt rating: historically 9, currently 3

Ever since I heard about unit testing I’ve seen the appeal, but I didn’t start to use
it regularly until 2005 when I joined Clearswift and met Stuart. Until then, I hadn’t heard about mock objects
which I find absolutely crucial in unit testing. I had read articles and seen examples of unit tests, but everything seemed to fall
apart when I tried to write my own – everything seemed to need something else. Of course, taken to extremes this is often a fault
of the code itself, where some classes require a complete system to be up and running before they can do anything. Unit testing
such a beast is difficult to say the least. In other situations you merely need to be able to specify a collaborator, which is where
mock objects come in.

So, since finding out about mock objects I’ve been more and more keen on unit testing. I know it’s not a silver bullet – I know that more
testing is required, both at an integration level between components, and at a system level, sometimes including manual tests. However,
once I started unit testing regularly, I got a sense of just how often code which I’d assumed would work simply wouldn’t. I’ve seen examples
of code which could never have possibly worked, with any input – so they can’t possibly have been used, or the results weren’t actually
important in the first place.

These days, I get frustrated when I either have to work with code which isn’t under test and can’t be easily put under
test due to the design (see point 7 on Eric’s list, excessive coupling) or when I’m writing code which is necessarily difficult to test.
Obviously I try to minimise the amount of the code which really can’t be tested – but sometimes it’s a significant amount. Urgh.

I currently don’t have many tests around my Miscellaneous Utility Library. I’ve
resolved to add tests for any new features I add or bugs I find though. Someone mailed me about a bug within the Utf32String
class. In the process of writing a unit test to demonstrate that bug I found at least two or three others – and that wasn’t even
trying to exercise the whole code, just enough to get to the original bug. I only mention this as a defence against the “I don’t need
unit tests – my code doesn’t have bugs in it” mentality. I would really like to think that I’m a pretty good coder – but everyone mistakes.
Unit tests won’t catch all of them, but it gets an awful lot. It also acts as documentation and gives you a much better base on which to
refactor code into the right shape, of course…

#4 – Using the wrong tool for the job

Personal guilt rating: 3

“When all you have is a hammer, everything looks like a nail.” That’s the typical quote used when tackling this topic. I hope this
sin is fairly self-explanatory. If all you know is Java and C#, you’ll find it a lot harder to solve problems which are best solved
with scripts, for instance. If all you know is C, you’ll find writing a complex web app a lot harder than you would with Java or
.NET. (I know it’s doable, and I used to do it – but it was really painful.) If you’re writing a device driver, you’ll find life
sucks pretty hard if you don’t know C or C++, I suspect.

Using the wrong tool for the job can be really damaging in terms of maintenance. While bad code can often be refactored into
good code over time (with a lot of effort) there are often significant implications in changing implementation language/technology.

This is a really good reason to make sure you keep yourself educated. You don’t need to necessarily keep up to date with all
the buzzword technologies – and indeed you’d find you did nothing else if you tried to keep up with everything – but there’s
always plenty to learn. Recently I’ve been looking at
Windows PowerShell
and Groovy. Next on my list is Squeak (Smalltalk).
I’ve been promising myself that I’d learn Smalltalk for years – at a recent Scrum
training course I met yet another Smalltalk evangelist, who had come from the Java side of things. It’s got to be worth trying…

#5 – Excessive code pride

Personal guilt rating: 2

I was recently pair programming and looking at some code Stuart had written a couple of weeks before. There were various bits
I wasn’t sure about, but thought were probably a bit smelly, and I asked my pairing partner to include a lot of comments
such as // TODO: Stuart to justify this code and
// TODO: Stuart to explain why this test is useful in the slightest. It’s worth bearing in mind at this point that
Stuart is significantly senior to me. With some people, comments like this would have been a career-limiting move. Stuart,
however, is a professional. He knows that code can usually be improved – and that however hard we try, we sometimes take
our eyes off the ball. Stuart had enough pride in his code to feel a need to fix it once the flaws had been pointed out,
but not enough pride to blind him to the flaws in the first place. This appropriate level of pride is vital when you’re working
with others, in my view. I don’t mind if people change my code – assuming they improve it. I expect that to happen
at a good code review, if I haven’t been pairing. A code review which is more of a rubber stamp than anything else is just a
waste of time.

This doesn’t mean I will always agree with others, of course. If I think my design/code is better than their suggested
(or even committed!) change I’m happy to put my case robustly (and with no deference to seniority) – but usually if someone’s
put in sufficient effort to understand and want to change my code in the first place, chances are they’ll think of something
I haven’t.

Write code you can be proud of – but don’t be proud to the point of stubbornness. Be prepared to take ownership of code you write
in terms of being responsible for your own problems – but don’t try to own it in terms of keeping other people out of it.

#6 – Failing to acknowledge weaknesses

Personal guilt rating: 2

ASP.NET, JSP, SQL, Perl, COBOL, Ruby, security, encryption, UML, VB… what do they all have in common? I wouldn’t claim
to “know” any of them, even though I use some on a regular basis. They are just some of my many technological weak spots.
Ask me a question about C# or Java in terms of the languages and I’ll be fairly confident about my chances of
knowing the answer (less so with generics). For lots of other stuff, I can get by. For the rest, I would need to immediately
turn to a book or a colleague who knows the subject. It’s important to know what you know and what you don’t.

The result of believing you know more than you actually do is usually writing code which just about works, at least in
your situation, but which is unidiomatic, probably non-performant, and quite possibly fails on anything other than the
data you’ve given it.

Ask for help when you need it, and don’t be afraid to admit to not being an expert on everything. No-one is an expert
at everything, even though Don Box does a pretty good impression of such a person…

#7 – Speaking with an accent

Personal guilt rating: 6 (but conscious and deliberate in some places)

Some of the worst Java code I’ve seen has come from C++ developers who then learned Java. This code typically
brings idioms of C/C++ such as tests like if (0==x) (which is safer than if (x==0) in C as missing
out an equals sign would just cause an accidental assignement rather than a compiler error. Similarly, Java code which
assumes that double and Double mean the same thing (as they do in C#) can end up behaving
contrary to expectations.

This is related to sin #6, in terms of people’s natural reaction to their own ignorance: find something similar that
they’re not ignorant about, and hope/assume that the similarities are enough to carry them through. In a way, this can
make it a better idea to learn VB.NET if you know Java, and C# if you know VB. (There are other pros and cons, of course –
this is only one tiny aspect.)

One way of trying to make yourself think in the language you’re actually writing in rather than the similar language you’re
more familiar with is to use the naming conventions of the target language. For instance, .NET methods are conventionally
PascalCased whereas Java methods are conventionally camelCased. If you see Pascal casing in Java code, look for other C#
idioms. Likewise, if you see method_names_with_underscores in either language, look for C/C++ idioms. (The most obvious C
idiom is likely to be checking return codes instead of using exceptions.)

Naming conventions are the most obvious “tell” of an accent, but sometimes it may be worth going against them deliberately.
For instance, I like the .NET conventions of prefixing interfaces with I, and of using Pascal casing for constants instead of
JAVA_SHOUTY_CONSTANTS. It’s important when you favour this sort of “breakaway” behaviour that you consult with the rest of
the team. The default should always be the conventions of the language you’re working in, but if the whole team decides that
using parts of a different convention helps more than it reduces consistency with other libraries, that’s reasonable.

What isn’t so reasonable is breaking the coding idioms of a language – simply because they other languages’ idioms
tend not to work. For example, RAII just doesn’t work in Java, and isn’t
automatic in C# either (you can “fake it” with a using statement, but I’m not sure that really counts as RAII).
Idiomatic code tends to be easier to read (particularly for those who are genuinely familiar with the language to start with)
and less semantically troublesome than “imported” styles from other languages.

Conclusion

So, that’s the lot. Ask me in a year and I may well have a different list, but this seems like a good starting point.
I’ve committed every sin in here at least once, so don’t feel too guilty if you have too. If you agree with them
and are still breaking them, that’s worth feeling a bit guilty about. If you disagree with them to start with,
that’s fair enough – add a comment to say why :)

PowerShell in Action

Every so often, I review books for publishers at various times before they hit the streets (anything from initial proposal to final review). The book I’ve been reviewing most recently is PowerShell in Action. (For those of you who didn’t see the news, PowerShell is the new name for Monad, the new object-oriented shell for Windows.)

Now, I’m excited about PowerShell as a product, but I’m even more excited about the book. I’m a pretty harsh reviewer, and I can only think of about three books which I’ve reviewed and been really positive about throughout most of the review. This is the best of them. I’ve not seen the whole book yet, but from what I’ve seen it’s going to be both readable and informative, which is frankly a rare combination in technical books. The author (Bruce Payette) is on the PowerShell team, so we get the information straight from the horse’s mouth (no disrespect meant) along with reasons for design decisions. Anyway, go and have a look at the home page for the book (linked above), read the first (unedited chapter), and sign up for updates. It’s going to be fab.

Groovy

Updated 7th August 2006 – It looks like closures aren’t meant to require K&R bracing after all. Hoorah! Examples changed appropriately.

One of my tasks at work is to investigate new languages and technologies and report back what
use we might make of them, where they fit in with what we’re doing, and generally what I think
of them. Obviously some of this will be specific to Clearswift,
but I’d like to make as much “insensitive” information available as possible. This post is my first
“report” as such, on Groovy.

What is Groovy?

From the Groovy home page:

Groovy is an agile dynamic language for the Java Platform with many features that inspired languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax.

That doesn’t help much if you don’t know Python,
Ruby or Smalltalk.
However, the key words (for me at least) in the above are Java and dynamic.
The Java bit is important to me because I know Java pretty well – both in terms of
the language and the standard library. It’s always nice not to have to learn yet
another way of doing the same things. (There are extra things to learn
in Groovy, but they are small in comparison with learning a platform from scratch.)
The dynamic bit is important because it’s what differentiates Groovy from Java in the first place.

Compared with, say, C and C++, Java is already pretty dynamic. It’s very easy to load classes
on the fly (it’s pretty easy to generate them, even) and reflection allows you to examine classes
at runtime. This allows for frameworks like Spring,
Hibernate and JUnit.
However, Groovy allows “dynamic typing” (an oft-contended phrase, but more later) and various
bits of what are effectively syntactic sugar to make the code terser. Most importantly from my
point of view, it offers closures – the equivalent of C# 2.0’s
anonymous methods.
(This removes the need for most inner classes in Java.) There are various other handy features too,
which generally make Groovy simpler to work with. Most of this post is effectively just a list of
features with examples and discussion.

Compiled, but scripty

Groovy is compiled to Java byte-code, but can be written as a script as well. Normally, the
whole script is compiled at start-up (as far as I can tell), although a lot of decisions are
left to run-time, so typos etc can sometimes only show up when a line is executed, even though
in a more “static” language they would have been caught at compile-time. Groovy scripts are
(commonly) executed using the groovy tool. There are also tools for running Groovy
as an interactive shell (groovysh) and a similar tool wrapped up in a GUI
(somewhat confusingly called groovyconsole). The groovyc tool is
provided to compile Groovy into bytecode to be used later rather than just run immediately.
The input to the compiler doesn’t have to be a fully-fledged class as such – it can just be a normal
Groovy script, in which case a class with an appropriate Main method is created.

It’s customary at this point to have a “Hello World!” program. As you can use Groovy like a scripting
language, it’s particularly simple:

println "Hello World!"

Saving the above to a file (e.g. test.groovy) and invoking with groovy test.groovy
gives the expected result. Things to note:

  • No class declaration, import statements etc. It’s just a script.
  • println is used instead of System.out.println. I believe this is a
    call to the println method which has been “added” to java.lang.Object.
  • No brackets and no semi-colon. You can use them – you can make them Groovy like very much like Java
    for the most part, but you don’t have to. I tend to use brackets but often omit semi-colons. You
    don’t even have to use brackets when there are multiple parameters.

As programs like the above are so convenient, I’m likely to use the features listed there in the
samples below. Other than that, I’ll attempt to only use one new feature at a time where possible,
so it’s obvious what I’m demonstrating.

Closures

In my limited experience with Groovy, closures form the single most useful feature of Groovy. They
allow you to specify some code (which may take parameters and return values) and then encapsulate that
code as an object – so you can pass it as a parameter to a method, for instance. The method could then
call the encapsulated code, and so forth. C# 2.0 provides this feature in the form of anonymous methods
(as delegate implementations) but in normal Java one would typically use an anonymous inner class, which
can end up being very ugly due to all the extra “gubbins” of specifying the superclass and then overriding
a particular method. Here’s possibly the simplest example of a closure:

Closure c = { println ("Hello closure!"); }
c();

Giving all the details of what closures can and can’t do would take pages and pages, so I’ll just mention
a few broad points. Local variables are captured as in C#’s anonymous methods (so are writable, unlike
local variables being used in anonymous inner classes in Java), and access to private members
of the enclosing class is also permitted. Closures taking a single parameter can use the implicit parameter
name of it:

Closure printDouble = { println (it*2) }

printDouble(5)
printDouble(10)

Closures taking more than one parameter can specify their names in a sort of “introductory section”:

Closure printProduct = { x, y -> println (x*y) }

printProduct (2, 3)
printProduct (4, 5)

Finally, a very common idiom in Groovy is to make the last parameter of a method a
closure. In this case, you can call the method specifying all the other parameters normally, and then specifying
the closure parameter as code which appears to be after the method call. This takes a little while
to get used to, but is really, really handy. Here’s an example:

// Declare the method we're going to call
void executeWithProduct (int x, int y, Closure c)
{
    c(x*y);
}

// Call it with a closure that prints out the result
executeWithProduct (3, 4)
{
    println (it);
}

Groovy uses closures extensively, so they will come up out of necessity in a lot of the following examples.

“Loose typing”

Groovy doesn’t require you to specify the types of variables very often. Lots of magic happens to convert things
at the right time. Indeed, method overloading appears to be performed at run-time rather than compile-time. The
exact nature of how loose the types are is currently a mystery to me, and the specification is somewhat inadequate
in this regard. However, it’s worth looking at a few examples:

Simple hello world using loose typing (the differences when you use def are beyond the scope of this introductory article):

a = "Hello"
def b = " World!"
println (a+b)

Dynamic method overloading:

void show(String x)
{
    println ("string: "+x)
}

void show(int x)
{
    println ("int: "+x)
}

void show(x)
{
    println ("???: "+x)
}

y = "Hello"
show(y)
y = 2
show(y)
y = 2.5
show(y)

Results:

string: Hello
int: 2
???: 2.5

String interpolation

Groovy uses the GString class (I kid you not) for string interpolation. Double-quoted
strings are compiled into instances of String or GString depending on whether
they contain any apparent interpolations, and single-quoted strings are always normal strings. (If you
need a character literal, it looks like you need to cast.) Any Groovy expression can be part of
the interpolation, which is enclosed in ${...} (like Ant properties). The braces appear
to be optional for simple expressions (the definition of which I’m not prepared to guess).

x = 10
y = "Jon"

println ('x is $x') // No interpolation with single quotes
println ("x is $x") // Simple interpolation
println ("y is ${y.toUpperCase()}") // Method call

Results:

x is $x
x is 10
y is JON

Collections: syntactic sugar and extra methods

Groovy makes working with collections easier, by providing syntax for lists and maps
within the language itself, and by using closures to make life easier. List and
map initializers both go in square brackets, with maps using a colon between a name and
a value. Also, number ranges are available as start..end. Note that
a number of common Java packages are imported by default, which is why the following
code doesn’t have to specify java.util anywhere.

List list = [0, 1, 4, 9]
Map map = ["Hello" : "There", "a" : "b"]
List range = 0..3 // Equivalent to [0, 1, 2, 3]

Indexers are provided (just like in C#) so using the above, map["Hello"] would give "There"
and list[2] would give 4. The collections also have a number of
extra methods added to them, many of them
involving closures. For instance:

list = 1..7

// Execute the closure for each element
// Output: 2, 4, 6, 8, 10, 12, 14 (on separate lines)
list.each
{
    println (it*2)
}

// Find the first element where the returned value is true
// Output: 6
println list.find 
{
      return it > 5
}

// Find all elements where the returned value is true
// Output: [6, 7]
println list.findAll
{                    
    return it > 5
}

// Transform each element, creating a new list
// Output: [1, 4, 9, 16, 25, 36, 49]
println list.collect
{
    return it*it
}

There are more – see the link above.

IO

Another aspect of the JDK to be given the closure treatment is IO. Groovy makes it
really easy to read each line of a file and execute some code on the line, for example.
Here’s a program which (assuming it’s in a file called test.groovy) prints
itself out with the line numbers:

int line=1
new File ("test.groovy").eachLine 
{
    println "${line}: ${it}"
    line++
}

Enhanced switch statements

In Groovy, switch statements can have cases which are collections (including ranges; the case matches
if the switch value is in the collection), types (the case matches if the value is an instance of the type),
regular expressions, and falls back to equality otherwise. In fact, you can add your own type of case testing
by implementing an isCase method, making switch/case very flexible indeed. I haven’t tested it, but
I doubt this is nearly as efficient as the normal Java switch/case – but Groovy is about simplicity of
expression more than ultra-efficiency.

Categories – aka C# 3.0 extension methods

Groovy allows you to pretend that a class has a method you wish it had. It’s all pleasantly scoped so
you won’t do it accidentally. Here’s an example:

// Define the extra method we want
class IntegerCategory
{
    static boolean isEven(Integer value)
    {
         return (value&1) == 0
    }
}

// Use it - in a cleaner looking way than
// explicitly calling the static method.
use (IntegerCategory.class)
{
    println 2.isEven()
    println 3.isEven()
}

Groovy Markup

There are many times when you need to build a hierarchical structure of some kind. Groovy introduces
the idea of “builders” which help. For instance, for XML, there’s the DOMBuilder class
(along with SAXBuilder and NodeBuilder, the latter of which allows
easy XPath-like navigation). Using DOM to build XML in Java is a complete nightmare, and while
dom4j and JDOM are definite
improvements, they still don’t make it quite as easy as this. Suppose you have a map of names to ages,
and you want to build an XML document representing that information. Here’s a sample script in Groovy to
demonstrate how easy it is (using MarkupBuilder, which writes the generates XML out for you).
Elements are added just by calling a method of the same name (Groovy responds to the method call as if the
method were available normally, even though obviously it doesn’t know in advance what your element names
will be), and attributes are specified using a map in the method call. Child elements are specified
within closures.

import groovy.xml.*;

Map nameAgeMap = ["Jon": 29, "Holly": 30, "Dave": 32]

builder = MarkupBuilder.newInstance()
builder.rootElement
{
    names
    {
        nameAgeMap.each 
        {
            entry ->
            person ("name": entry.key, "age": entry.value)
        }
    }
}

Result:

<rootElement>
  <names>
    <person name='Holly' age='30' />
    <person name='Dave' age='32' />
    <person name='Jon' age='29' />
  </names>
</rootElement>

Ant integration

I’m a big fan of Ant, but
every so often it just doesn’t let me do everything I want easily. Sometimes I want to be able to execute
some code, but I don’t want to go through the hassle of having to make sure I’ve compiled something which
is only actually going to be used by the build procedure anyway. Groovy to the rescue! You can embed
Groovy code “in-line” or call out to a Groovy script. Note that Ant allows many scripting languages (anything
supported by BSF, for starters) to be used. Groovy may be
more familiar-looking to developers who are familiar with Java but don’t know any scripting languages.
Groovy supports Ant directly in terms of providing access to the current project and properties, and the
AntBuilder class works in a similar way to the builders mentioned above, allowing Ant tasks
to be dynamically created and executed. Here’s a sample Ant file (which assumes that groovy-all-1.0-jsr-05.jar
is in the same directory):

<?xml version="1.0" ?>   
<project name="groovy-test" default="test" >

  <taskdef name="groovy" 
         classname="org.codehaus.groovy.ant.Groovy"
         classpath="groovy-all-1.0-jsr-05.jar"/>
  
  <target name="test">
    <groovy>
      println "Running in Groovy"
      
      fs = ant.fileset (dir: ".", casesensitive: "no") 
      {
          include (name: "*.groovy")
          include (name: "*.java")
          exclude (name: "Test.*;test.*")
      }
      
      fs.toString().split(';').each 
      {
          ant.echo (it)
      }
    </groovy>
  </target>                               
  
</project>

Results:

Buildfile: build.xml

test:
   [groovy] Running in Groovy
     [echo] Benchmark.java
     [echo] CommandTest.java
     [echo] Handler.java
     [echo] Main.java
     [echo] MyEnum.java
     [echo] test2.groovy
   [groovy] statements executed successfully

BUILD SUCCESSFUL
Total time: 1 second

Other bits and bobs

There’s a lot more to Groovy than what’s presented above. It has operator overloading, syntax to
make regular expressions and multi-line strings easier, simple property definition and access, built-in
JUnit integration, an XPath-like expression language and much more besides. Read the home page for some of these – but be warned that some features are
pretty well hidden.

So, what’s wrong with it?

In general, I like Groovy. I’m not convinced that the productivity gains from it are worth the
downsides for major apps, but it’s really handy for getting something small working quickly. It could
be really great for prototyping. I may well eventually be convinced that “dynamic typing” isn’t
that dangerous really, and doesn’t have a detrimental impact on the usability of libraries, etc. Only
time will tell.

In the meantime, however, Groovy does suffer majorly from a lack of polish. There are plenty of bugs
to be found, and the documentation is terrible. (The members of the mailing list are more than happy to help, and a major documentation update is under way, however.) There are aspects of the syntax which seem to be
overkill, creating complexity without a huge benefit, and there are bits of normal Java which are
just “missing”. (Normal for loops aren’t available in the version I’m using, although
I believe they will be in the next available release. You can use a loop such as for (i in 0..9),
but not for (int i=0; i < 9; i++).) Things like this should really be fixed to make
as much of normal Java as possible available within Groovy.

I don’t mind the fact that Groovy isn’t finished – my worry is that it may never really be finished.
I really hope that I’m wrong, and that it will be all done and dusted (for v1) in the summer.
There’s no lack of activity – the community is very lively – but activity doesn’t necessarily indicate
actual progress towards a goal. Since originally posting this blog entry, I have been assured that
real progress is being made, so I’m keeping my fingers crossed.

Links

  • Groovy home page
  • “Groovy JDK” – the extra methods added to various classes
  • Grails – Groovy/Spring/Hibernate-based web application devlopment

Faith blog

I decided today that I could do with somewhere to dump random thoughts about my faith in the same way that I dump random thoughts about computing here. Clearly this isn’t the right place to do it, so I’ve set up a Faith Blog with Blogger. Some of you may be interested in it. Don’t let it bother you if not. This is the last you’ll hear about it unless there’s some topic which directly affects both areas.