Jan 29

After nearly 10 years of working on complex systems I think I have nailed down why poorly formatted code annoys me so much. It wastes time. Complex logic requires whitespace in order for the reader to make sense of it in the same way that punctuation is used in sentences. If the whole thing looks like a dog’s breakfast, it makes it more difficult to understand.

When a person approaches poorly laid out code, they have two choices:

  • battle through it
  • clean it up and make sense of it

The first one results in an exercise in frustration, the second… well, that’s a beast unto itself.

A long time ago, in my first job, I was working for a consultancy at a major telecoms company on a very large system. The system was used to activate telecoms products on individual lines and talked to telephone exchanges across the network. The project was in its tenth year and had fallen into a steady routine of releases. Regression tests had been written years earlier, but had long since fallen by the wayside. A new project manager came in with an agenda of improvement, and the process to get the tests running again began in earnest.

I was given the task of redeveloping telephone exchange simulators that the tests made use of. These Perl daemon servers would listen on a pipe, take some text in, interpret it and spit out what was expected of an actual telephone exchange of the appropriate manufacturer and version.

I had never worked on anything like this before and asked whether there was any documentation. The response as I remember it was “Bwahahaha! Documentation?”. OK, maybe not quite that dramatic, more along the lines of… “Nothing concrete but it has a lot of comments”.

Understatement of the millennium. Just a sample:

$i++; # add 1 to the value of i

Apparently, the project had taken on a contractor years previously who wasn’t particularly good. Rather than getting rid of him (they didn’t care as they were being paid by the hour for the bum on the seat), they got him to comment the code. Obviously annoyed that he was being sidelined, he commented every single line out of pure spite.

The code wasn’t great to begin with, but in this state it was unreadable! The first thing I did was strip out the redundant comments (some 20,000 lines worth) and checked in a clean copy. The next day one of the senior programmers and the version control manager gave me a a very stern talking to!

It seems that even though no one could argue with my intentions and everyone agreed that it was the right thing to do, it played havoc with the merge tracking. Everything had changed and it would now be impossible to see what my actual code changes were!

The same issue arises with non-standardized code. On a large project there are a lot of people working against the same code base. Some will be good, others not so much. Everyone iterates through each others classes, making changes as is warranted. Now imagine the scenario above, but with numerous people working on various branches of code that all have to be merged back together.

Your programmers now have the same choice:

  • do they slowly battle with illegible code in dealing with the task at , or
  • do they reformat and take up someone else’s time as they struggle to work out what of the multiple versions needs to go into the final release?

Not a pretty choice. But there is hope!

Actually apply a coding standard.

Give anyone who does not apply it a good talking to. You could establish one using current naming structures, layouts, consensus etc. But you will probably end up making life more difficult for yourself. Getting code formatters to behave just the way you want to and then getting those changes out to everyone on the team takes time, and in a project situation, that’s a rare commodity.

Using Java? Use the Sun standard. ALT-SHIFT-F will automatically format Java code to it by default in Netbeans, and CTRL-SHIFT-F does the same in Eclipse. Weird naming conventions are great for your pet project, but just use the defaults in real life. Personal preference has little relevance in reality. The curly brackets debate happened a long time ago, and no one won. I have used Jalopy in the past as a custom formatter where some weird conventions were dictated. Even though it was supposedly a standard, I realized that few other on the project team did the same, because it took too much time to set up and they didn’t know what the big deal was anyway… *sigh*

Use standard coding conventions. Keep a close eye on anyone who checks in nonsense because poor formatting is often an indicator of poor quality code in other ways, and it will take time to clean up their mess. Time that could be better spent bringing your project in on budget.

Jan 28

It is really fantastic when you get great service these days. I bought a bag for my kite board a couple of weeks ago from Extreme Kites in the UK, for an upcoming trip to Australia. Mike from the shop had a problem getting the right size bag in on time, and after finding out that I was heading off soon, contacted the supplier to ship me one directly. It came in by courier last week.

If you are in Ireland or the UK and are looking to pick up some kite surfing gear I hugely recommend them. I will be using them again.

Jan 25

Unit testing database code is a bit of a funny problem. Most developers can pretty easily get their heads around unit testing a piece of Java code using interfaces and mock objects. When it comes to database code or DAOs, it suddenly becomes particularly difficult. But why, what is so difficult about testing stuff against the database? Surprisingly enough, the answer is that it has nothing to do with coding or a particular framework, although these do play their parts. It comes down to a complex web of human interaction, version control and managing environments. Let me explain.

The standard unit test has three basic phases:

  • Setup (@Before)
  • Test (@Test)
  • Tear down (@After)

The first sets the test environment into an expected state, the second runs the test and checks that the outcome is as expected, while the final one clears up any test resources.

How does this relate to database testing? Let’s say that we have a DAO that performs a particular select statement. Our test should be to retrieve a particular number of records from a known set. Easy enough. The precondition of course, is that you have a known set to begin with.

It’s ALL about the environment.

Most large development projects go like this: The database guys update the schema. The developers write the code. The developers need a particular data set to exercise the various use cases so they add it to the schema. It all becomes a bit messy.

Eventually, very complex data sets are set up by everyone concerned in a primary schema that keeps getting updated. The database schema generally is not version controlled, as it is constantly being redefined using DDL statements run by the DBAs. Most of the time you will be lucky to get a backup of a schema, with all of the data truncated, as the schema and supporting code (i.e. the application) moves between environments.

Getting back to the test. You set up your data by hand in the master schema so that there were three items in the widgets table where some condition was true. You write your test, it runs against the schema, pulls out the expected three widgets and everything is great. You check in the tests. A week later your colleague, Bob, adds another widget to satisfy his test condition. Your test all of a sudden returns 4 items and the test breaks.

Of course, Bob didn’t actually run your test because he was too busy with his own and the test suite isn’t clean anyway because everyone is falling over each other.

Sound familiar?

What about inserts? The precondition: no sprockets were in the table, the test: insert a sprocket, the postcondition: a sprocket is in your table. Kind of hard to test under the above conditions isn’t it? For one thing, the exact data of the test sprocket may be in the table, so checking by value may give you false positives, while deleting it may get rid of more records than you wanted. What about concurrent tests? With a group of developers running the same tests, they start tripping over each other very quickly and the whole effort becomes an exercise in frustration. At this point the development manager throws up his hands, says that this automated testing thing is a load of bollocks and to get back to your work because they didn’t deal with all this when he was doing VB. Somewhere else, Kent Beck sheds a tear…

Let’s examine what goes on in Ruby on Rails. One of the best ideas that was popularized by this framework was its method for database unit testing. A developer’s workspace has multiple environments by default - development, test and production. You develop against the development schema, designing table structures, and playing with the user interface to your heart’s content. When you run unit tests, the following happens - the schema from development is copied into the test database with no data in it. The framework imports version controlled sets of test data (saved as YAML files) into this new schema. Whenever a test is run, it is guaranteed that the database will be in this state. Any changes a test makes are visible only within the scope of this one test. The tear down step cleans out your changes. This makes life so much simpler, especially if you have been working in the nightmare scenario above.

So how do we get the same sort of effect in a corporate development environment?

You need multiple database schemas in order to unit test your db code.

Pause and re-read that line. It’s not negotiable. Probably two per developer. One with sample data to use while you work on the user interface. The other, a temporary one for unit testing. A whole development team using the one schema does not work. Most projects do it, but that doesn’t mean that it’s a good idea.

Some suggestions for how to manage this. The DBAs have their own schemas. The full DDL for the database is kept in version control. After each change, the full database DDL is dumped and checked in. No UPDATE TABLE statements. Ever. This way you are guaranteed that if you ever want to get a baseline of your system, you can also rebuild the database as it existed at this time. I worked on a very large telecoms project with a huge development team, and this worked. Well.

The test data for your environments is stored in version control - at the very least, as dumps of insert statements. For unit testing purposes, a dedicated unit test framework is beneficial. DBUnit performs the same task in Java as described above for Rails - it loads test data from dumps (a number of formats are supported), and guarantees that the test database exists in the expected state when each test is run.

To test your database code, refresh your test schema with the one from version control - typically using your chosen build system. Ant tasks are generally pretty good for this. Now run your test cases. Gorgeous! No tripping over other people, and your tests are guaranteed to work the same each time. No excuses for a red bar.

So why is unit testing databases so difficult if it doesn’t have to be? Most of the time it involves process change and getting out of bad habits, not just a tool. And change means convincing people. Generally, managers do not understand what benefit there is in multiple database schemas, as it is seen to increase complexity and therefore risk, and DBAs like to have full control over what is going on on their servers. The topic of databases and processes is also a great one for religious zeal.

The process outlined above should explain the hows and whys to the individuals involved. The changes above mean a little bit more setup initially, but a saner development process.

A nice side effect is how easy upgrading databases through your environments can become. Run the latest DDL against a fresh schema, get the differences between it and your target environment using a database compare tool, and fire it off. Beautiful.

Jan 23

Bob Lee posted yesterday about one of his sessions at Javapolis (viewable at Parley’s), that covered heaps of good stuff about dependency injection and API design. At the end he mentions weak and soft references. What? Who? Not exactly a language feature that I have come across in the day to day, so I did a quick search and came up with this:

A weak reference is a reference that isn’t strong enough to force an object to remain in memory.

Hopefully, I can give a better explanation than that.

A strong reference is one that while it exists, the object won’t get garbage collected:

Goat goat = new Goat();

If the goat is referenced elsewhere and loses all other references, it will still stay in memory. This is a problem if you want to keep some other data around about the goat:

Map<Goat, GoatInfo> goatMetaData = new HashMap<Goat, GoatInfo>();
goatMetaData.add(goat, new GoatInfo("Billy"));

To ensure that you don’t keep goats around any longer than you have to, you would have to do some weird coding to ensure that that code that deals with goats cleans up the store. Something with listener classes or similar.

Enter the weak reference. You wrap your goat in it as such:

WeakReference weakGoat = new WeakReference(goat);
Goat goat = (Goat) weakGoat.get();

Alternatively:

WeakReference<Goat> weakGoat = new WeakReference<Goat>(goat);
Goat goat = weakGoat.get();

weakGoat will return null, once all the other references to goat have been set to null, and it has been garbage collected.

So that’s cool for a single instance. What about the metadata example above? Well, there is a Map implemenation that uses this feature.

Map<Goat, GoatInfo> goatMetaData = new WeakHashMap<Goat, GoatInfo>();
goatMetaData.add(goat, new GoatInfo("Billy"));

If you try to get the additional info about the goat once it has been garbage collected, the map will return null. Nifty.

Soft reference objects, on the other hand are cleared at the discretion of the garbage collector in response to memory demand. So while weak references will be cleaned when the garbage collector deems that the underlying object has gone, use of soft references means that they will hang around a bit longer until the memory space is needed for something else.

An object is phantomly referenced after it has been finalized, but before its allocated memory has been reclaimed. According to the API, they are “most often used for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism”.

The API has much more detail on how to use this, although it’s kind of tough to get your head around. Too many uses of the word “reference”.

Useful when you are writing a container or cache. But you don’t want to do that because you know that you can get open source ones off the shelf, right? ;)

Nice one to know for interviews. Real bastard to ask :)

—- Update 25/04/08

I got asked :)

Jan 21

First thing’s first. I love open source. I think that it’s the best thing since sliced bread. That thing that we were always told about since computer science, that of the open marketplace for components to be shared and reused HAS happened. Just not in the “buy this billing component” kind of way. It’s even better! It’s free (ish)! You download what you want and plug it in to your application. The quality varies, but if you keep your ear to the ground and do your homework, it will save you a lot of time. And time is money.

But just how much money?

I recently discovered Ohloh . It’s like professional networking, but not exactly, and it’s for open source. It has some cool features, but the one that got me instantly was that it trawls through open source repositories and gives you some very cool stats. Like just how much effort it would take to build an equivalent version of something, and how much it would cost given a yearly salary for a programmer. It uses lines of code, which are not a good metric, but rather an OK litmus test.

Another one of my favourite sites is Java-Source.net. Pick a particular category of software that you need, and it lists you a suite of open source options in Java - ready for you to do with as you will.

So let’s pick a category. Here’s one that I prepared earlier - workflow engines. Pretty much every place that I have ever worked has rolled their own in this regard. For some reason it’s considered a low hanging fruit (even though people write postgraduate theses on them). In some cases, off the shelf offerings are seen as overkill, too restrictive or just too complex. Most of the time the analysis is little more than gut feel, a kind of “Hmm… looks too hard, must have been over-engineered.” So a couple of guys get together and do a “bake at home” version. Pretty soon, the reality takes over and it doesn’t do what it’s supposed to, the use case was misunderstood, you need a management console, version control of process flows, different flows in different environments… uh oh! Suddenly, you spend a lot of time maintaining this beast.

So let’s do the stats and take the first handful of products listed on both sites (there are many others). These vary in the amount of activity going on, have quite varied features and uses - some plug in to applications, others are standalone orchestration engines. It’s not exactly scientific, but it’s interesting for illustration purposes. Let’s take the average programmer salary as $55000 (dollars, euro, pounds - it’s all about the sameish worldwide, so doesn’t really matter):

LOC = Lines Of Code

  1. Apache ODE. 108,547 LOC, 55 Person Years, $1,498,221.
  2. Taverna. 134,334 LOC, 33 Person Years, $1,832,157.
  3. jBPM. 286,618 LOC, 74 Person Years, $4,081,422.
  4. Enhydra Shark. 255,101 LOC, 65 Person Years, $3,576,525.
  5. OpenSymphony OSWorkflow. 48,303 LOC, 11 Person Years, $627,203.
  6. ObjectWeb Bonita. 67,916 LOC, 16 Person Years, $894,118.
  7. OpenWFE. 187,176 LOC, 47 Person Years, $2,608,592.
  8. WfMOpen, 152,557 LOC, 38 Person Years, $2,084,413.

The average cost of building a workflow engine?

155,069 LOC. 42 Person Years, $2,150,333.

Once again, this is completely unscientific. I have no idea whether the cost is over the lifetime of the product or initial development cost, whether management costs are included, we aren’t comparing apples with apples, and these are general purpose engines rather than a thing that does only the thing you want. But it does make for a very interesting question. Have you got the time and money to do this, or would you rather get on with the business problem at hand?

Enterprise software is a complex business. There are no shortcuts. There are no easy decisions. The landscape changes all the time. You have to weigh up support costs, training, extensibility, maintenance and skills.

My take on it? Someone did the heavy lifting already. Do yourself a favour and take advantage of it. If it doesn’t do exactly what you want, then the code is right there to change. You can always contribute it back, and if it’s good enough then it becomes the property of the community. The numbers are compelling.

Jan 20

A couple of folks have asked me how I got my old Blogger permalinks to work on the new blog. It’s super simple.

Under Options -> Permalinks in the admin console, add the following custom structure “/%year%/%monthnum%/%postname%.html”. You can then set up the little Blogger redirect/DNS cheat method I described in the last post and everything hums just as before. Too easy.

Jan 16

I finally took the plunge and switched over to this new domain (nice, isn’t it?) running on Wordpress. I can’t believe how easy it was. The initial setup was magic.

Download Wordpress. Set up a database, add a user, upload the zip file and extract, fire up the domain in a browser. The first page that comes up is a wizard that asks for the database details. You enter them, press OK, and… it’s done!

The latest version has an import function for popular blogging services - point it at the old url, push the button and voila! Blogger also provides a mechanism to redirect links to a custom domain. You are supposed to point your DNS server to Google, but if you don’t it will take you to your own hosting service (it’s cheating, but hey). If you want to tweak your URLs so that all of the old permalinks work, it’s easily done through Wordpress’ admin console.

The most time consuming thing was picking out a theme. Switching was like getting out of a Lada into a BMW. Brilliant piece of software.

Jan 16

New Year, New Home!

This blog is now moving onto a new domain - www.jakubkorab.net
If you RSS me, please update your feed to point to here.

See you on the other side!

Jan 16

Technology review published an article on a technology that will get new PC’s booting to a useable state in a few seconds as opposed to the couple of minutes that it currently takes - albeit with an operating system parallel to Windows.

http://www.technologyreview.com/Infotech/20072/?a=f

This has been a real pain for me, as I am in the market for a new laptop, and a quicker start up was high on my wish list. I don’t mind ditching Windows for a different OS either, having heard good things about the alternatives. However, when I did some scouting around on the net, the boot times for OSX and Linux weren’t much better. Sure you can spend ages tweaking everything to get a quicker start up, but I suffer from the classic modern ailment - being time poor. In other words, screw that. I can’t believe that somehow with all the advances in computing power, we have communally accepted our fate and have to suffer through twiddling our thumbs while waiting for the PC to start.

I want to be up and running now. And I don’t want to hear the line about the Hibernate settings. I turn my TV off. I want to do the same with my laptop, not switch it to some sort of low power setting. If anyone has a silver bullet out there for XP or another OS, I would love to hear about it.

Jan 15

Every once in a while I forget how to do something in UML. InformIT have a great guide on the use of the notation just for this purpose. Nice.

http://www.informit.com/articles/article.aspx?p=360441&seqNum=5&rl=1

« Previous Entries