Archive for July, 2006

It ain’t easy to be simple

Monday, July 31st, 2006

Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away (Antoine de Saint-Exupery)

Everything should be made as simple as possible, but not simpler (Albert Einstein)

What do these quotes, the Rube Goldberg machines, Occam’s Razor and the KISS principle have in common (Google and Wikipedia keep impressing me what you find by just searching for a simple little word)?
Well, they are all about SIMPLICITY (or lack thereof)!
Simplicity is also a central tenet in software engineering and development.
I’ve seen really great pieces of software that unfortunately were complex and awkward to use. I’ve seen classes that were simple to use, but that had so many different responsibilities that they were hard to understand and maintain. I’ve seen design rules that were supposed to make implementation for the programmers as easy as possible, but resulted in a big pile of overly redundant code (this is also not simplicity).
Simplicity is all about reducing this complexity as much as possible.
In software engineering, this principle should be applied wherever and whenever possible.
When designing and implementing, the class’s internals should be simple (not too much responsibility for a single class - this is where high cohesion comes into play), but also its interface should be simple (the Spring guys, for example, are doing a great job wrapping and simplifying complex third-party classes and components).
But this is also true for a system’s architecture. System components should be as simple as possible, resulting in probably more, but simpler components.
And last but not least, simplicity also makes sense for processes - the build process and the development process (I don’t want to use the agile buzzword here … oops, too late).
I think a good metric is, how easy it is to describe a component. If you can say in a few sentences, what a component does, then it is probably simple enough. This applies to classes, but also to system components or subsystems.
And a final note: the goal is avoiding complexity, not negating it.

The Cradle of Initialization

Thursday, July 27th, 2006

First of all I’d like to announce, that (as a result to a suggestion for improvement) it’s not necessary any more to subscribe in order to post comments on this blog - so please feel free to put your oar in (you too, Mario)!
Ok, todays post started off as a question from my colleague Chris about what would happen in Java if an Exception was thrown in the constructor. And it ended with, well … read for yourself.
After we decided that Java’s behaviour in case of an Exception in the constructor was still quite decent, the next step was to have a look at class initialization - what happens if an Exception is thrown in the static initializer for example.
First Attempt: we try to throw a RuntimeException (something gives me the feeling, that only an unchecked Exception will work here):

	...
	static {
		throw new RuntimeException("oops");
	}
	...

Hey, not even a RuntimeException works. The compiler complains about the initializer not completing normally. Of course not, stupid compiler! That’s what we wanted!
But we wouldn’t be in the software business if we hadn’t fooled the compiler once or twice.
Second Attempt:

	...
	static {
		if (true)
			throw new RuntimeException("oops");
	}
	...

Gotcha, smart ass! When we try to run our class (added a main method for that), we get an java.lang.ExceptionInInitializerError. That’s what we wanted.
Third Attempt:
Not much unexpected behaviour yet. What can we do now. Hmmm … I remember someone saying, that it’s a bad idea in a constructor to expose this (the object currently being constructed) to another object (or even thread).
Ok, if that’s a bad idea, then exposing an object from inside the static initializer must be a very bad idea. So, let’s go.
A “good” way to expose an object is to register it in some registry. So we start with this registry:

public class Registry {
	private static SelfRegistered registered;

	public static void main(String [] args) {
		try {
			SelfRegistered.init();
		} catch (ExceptionInInitializerError err) {
			err.printStackTrace();
		}
		registered.hello();
		SelfRegistered registered2 = new SelfRegistered();
		registered2.hello();
	}

	public static void register(SelfRegistered selfRegistered) {
		registered = selfRegistered;
	}
}

And then the class, that creates an instance in the static initializer and registers it in the registry.

public class SelfRegistered {
	static {
		Registry.register(new SelfRegistered());
		// in some cases, something happens
		if (false) throw new RuntimeException("oops!");
	}

	public static void init() {
		// do some init stuff
	}

	public void hello() {
		System.out.println("Hello from " + this);
	}
}

So if we run the Registry class, the SelfRegistered.init() method is called, which does actually nothing, except that it of course causes the SelfRegistered class to be loaded and initialized. So before the init method does its nothing, the static initializer is executed, creating a new SelfRegistered() and registering it in the registry. The Exception is of course not thrown, because the condition can never evaluate to true.
Then, after the static initializer and the init method, we are back in the Registry.main method, where the hello method is first called on the registered object, and then on another instance of the SelfRegistered class.
We run it, and we get something like:

Hello from SelfRegistered@57f0dc
Hello from SelfRegistered@32c41a

Last Attempt:I have the feeling, that we are on the right way, so let’s quickly see what happens if the RuntimeException is thrown in the static initializer. So change the line in SelfRegistered to:

		if (true) throw new RuntimeException(”oops!”);

… and run it!
Wow … the output looks like this:

java.lang.ExceptionInInitializerError
	at Registry.main(Registry.java:8)
Caused by: java.lang.RuntimeException: oops!
	at SelfRegistered.(SelfRegistered.java:7)
	… 1 more
Hello from SelfRegistered@6a55fa
Exception in thread “main” java.lang.NoClassDefFoundError
	at Registry.main(Registry.java:13)

So if we carefully read this (with the other eye on our code), we see that during initialization of the SelfRegistered, after registering an instance of this class in the Registry, the RuntimeException was thrown, which caused class initialization to abort.
After catching this error, we try to call a method on the registered object, and - surprise surprise - it works!
But the class cannot be completely initialized, can it? The static initializer failed!
Well, of course it is not initialized, as we can see in the next lines, where we are trying to create a new instance of SelfRegistered - which fails.
The Moral:
What we learn here is, that it’s usually not a very good idea to expose an object from inside a constructor or even static initializer. This gets even more dangerous if Exceptions may occur (which is practically everywhere, as we know).
But the most important lesson is that even Java does not always behave the way we would like it to …

TODO or not TODO?

Tuesday, July 25th, 2006

Despite the already very ambitious subtitle of this blog Daily Dose of Software Engineering - and I mean the Daily part -, especially considering my posting habits in the past, I somehow managed to write my second post in just one day! Maybe a good omen…
This one is about a feature of an automatic build process.
We all know, that an automatic build process is a good thing (at least we should know by now). Along with the right tool and plugins, it makes sure that the code always compiles, the unit tests produce a green bar, the coding guidelines are respected by all developers and certain metrics are in a valid range.
Another feature that should be used much more often is, that pending implementation tasks (those nice TODO comments that a developer can put into his code if he is not really done yet) can easily be managed. Developers are usually very diligent adding such comments (mostly to defer dull or complicated tasks for later), and build tools have very good support for creating lists of those TODOs.
The problem is usually, that those comments are added to the code, the task lists are created, uploaded to the project’s developer web site, and … well, stay there without ever being checked (in the hot phase of a project, which is usually always, nobody wants to find some more skeletons in the project’s closet).
Here are some ideas that might help prevent this problem:

  • If you don’t do that already, add those TODO comments whenever you defer some implementation task for later, and use your build tool to create a publically available list of those implementation tasks
  • Before a release, the developers are responsible for checking their tasks, if they are relevant to this release (note, that you need to know, which tasks belong to which developer) and complete them if necessary (and then of course remove the TODO tags)

If these simple rules are obeyed, chances are small that your test team finds a bug, the developer looks for a possible fix, just finding a TODO comment saying exactly what should have been done in the first place to prevent this bug.
Finally, just a little story about a TODO comment we found some time ago - it was something like

  /*
   * TODO change this by version 5.3
   */

Well, believe it or not, we found it while adding some features for version 5.8 ;-) .
So back to our question TODO or not TODO? - the answer is definitely TODO!

Blogging Revisited

Tuesday, July 25th, 2006

So this is another attempt to get my blog going (should I say rolling?). If you’d have been on this site before, which you probably haven’t, you would have seen an installation of a simplePHPblog with exactly one blog post. In this post I promised to post more often than on the site I had before (which was actually a WIKI with 6 pages or so).
Well, so much for this promise - it didn’t quite work out the way I wanted it to.
Ok, as you can see, I just installed WordPress which I always wanted to have - unfortunately I didn’t have access to a database on my provider’s server. Well, now I do, and - et voila - WordPress to the rescue.
But enough of this now - I do not want to bore you with the long story about my first trial (and errors) concerning my site. Just as much, in future posts, I will try not to impose too much dull information upon you about my private life, my brand new car or my digestive system.
This blog is about software, and it is about software only.
There will be posts on Java, development tools, development process, object oriented stuff and software engineering in general.
So stay tuned for more…