« November 2003 | Main | January 2004 »

December 29, 2003

Generics

Listen to this articleListen to this article

Now I'm sure you're all bored to tears with yet another blog on generics but I felt it was only fitting to convert all my example code.

So, here is what the immutable collection examples turned out like:

public class Component {
    private final Collection<Component> _subComponents;

    public Component(Collection<Component> subComponents) {
        Assert.isTrue(subComponents != null, "subComponents can't be null!");
        _subComponents = Collections.unmodifiableCollection(
                Arrays.asList(subComponents.toArray(new Component[subComponents.size()])));
    }

    public Collection<Component> getSubComponents() {
        return _subComponents;
    }
}

Interesting. Because I wanted to use Collections.unmodifiableCollection(Collection<T>) it now needs to know the types. So I had to use the T[] Collection.toArray(T[]) method instead.

Or we could make it ever clearer:

public class Component {
    private final Collection<Component> _subComponents;

    public Component(Collection<Component> subComponents) {
        Assert.isTrue(subComponents != null, "subComponents can't be null!");
        List<Component> temp = new ArrayList<Component>(subComponents.size());
        temp.addAll(subComponents);
        _subComponents = Collections.unmodifiableCollection(temp);
    }

    public Collection<Component> getSubComponents() {
        return _subComponents;
    }
}

And of course my original bitch about custom type-safe collections:

Collection<Customer> customers = ...;
for (Iterator<Customer> i = customers.iterator(); i.hasNext(); ) {
    doSomething(i.next());
}

Not bad. Feels like C++ again ;-). Not sure if that's such a good thing or not.

As Damian Guy points out, we could do even better using the new for construct provided by 1.5:

for (Customer c: customers) {
    doSomething(c);
}

Now that definitely looks much nicer! Unfortunately I don't have a runtime that will support this - I can't seem to get J2SDK 1.5 to install on Gentoo :-(

Looking over all my newly re-written (that's re-factored for you buzzword bingo players) code, I have to say it reads pretty well. Time will tell if it really does add much more than using the old collection classes.

One thing I will note is that it's nearly impossible to copy and paste the examples for publishing as html. I have to change all the < and > to &lt; and &gt; respectively. Just putting that previous sentence in was a job and a half! hehehe

And lastly, I'm using IntelliJs support for generics using the 2.2 early access compiler from Sun. So no doubt things will change by the time they're released in J2SDK 1.5 proper.

December 28, 2003

Immutable Collections

Listen to this articleListen to this article

Oh what joy. Back on the last week of my project from a brief break for xmas and straight to the inevitable cvs update. Yikes!

This is probably old hat to a lot of you but for all others, Collections.unmodifiableCollection() and its siblings don't actually make a collection immutable!

By way of example, the following code is broken:

public class Component  {
    private final Collection _subComponents;

    public Component(Collection subComponents) {
        Assert.isTrue(subComponents != null, "subComponents can't be null!");
        _subComponents = Collections.unmodifiableCollection(subComponents);
    }

    public Collection getSubComponents() {
        return _subComponents;
    }
}

Looks pretty good but unfortunately, the following test breaks:

public void testImmutability() {
    Collection originalSubComponents = new HashSet();

    Component component = new Component(originalSubComponents);

    Collection returnedSubComponents = component.getSubComponents();

    assertNotNull(returnedSubComponents);

    // First, we test to see if the returned collection is immutable
    try {
        returnedSubComponents.add(new Object());
        fail("sub components should be unmodifiable");
    } catch (UnsupportedOperationException e) {
        // Pass
    }

    // Next, we test to see if we can subvert the immutability
    // by addding to the original collection
    assertTrue(returnedSubComponents.isEmpty());

    originalSubComponents.add(new Object());

    assertTrue("sub components should be a defensive copy", returnedSubComponents.isEmpty());
}

We haven't made a defensive copy! So let's add a little more code to get the test to pass:

public class Component  {
    private final Collection _subComponents;

    public Component(Collection subComponents) {
        Assert.isTrue(subComponents != null, "subComponents can't be null!");
        _subComponents = Collections.unmodifiableCollection(Arrays.asList(subComponents.toArray()));
    }

    public Collection getSubComponents() {
        return _subComponents;
    }
}

Remember, anytime a caller passes you a mutable object (such as Collection, Date, Calendar, etc.), you need to make a defensive copy if you're going to hold on to it. This will ensure no one accidentally subverts your own immutability.

Why did I use Arrays.asList() to create the copy? Well I'm glad you asked:

  • Because I know the collection will never be modified (that's what immutable means after all), I don't need to maintain the semantics of the original collection (which may have been a Set for example);
  • The resulting List will be have been created with exactly the right size to accomodate the contents of the collection, meaning no re-allocating buffers. As a reader points out the standard ArrayList constructor that takes a collection as an argument will allocate an additional 10%;
  • Arrays List implementation performs well when iterating; and;
  • The iteration order is preserved (if that was important).

It is also possible to use new ArrayList(int) followed by ArrayList.addAll(Collection), which is probably easier to read?:

public class Component  {
    private final Collection _subComponents;

    public Component(Collection subComponents) {
        Assert.isTrue(subComponents != null, "subComponents can't be null!");
        List temp = new ArrayList(subComponents.size());
        temp.addAll(subComponents);
        _subComponents = Collections.unmodifiableCollection(temp);
    }

    public Collection getSubComponents() {
        return _subComponents;
    }
}

As one reader has demonstrated, on his version of the JDK it uses an iterator which is the way I had assumed it would be implemented but I was thrown off when I looked at the source code for the version of the JDK I have and discovered that it creates a temporary array. Either way this post wasn't really about performance so I guess I'm getting a little off track now.

P.S. Anyone see the funny side of this test given my previous post?

Be gone ye foul smelling custom type-safe collections!

Listen to this articleListen to this article

I used to use STL type-safe collections in C++ all the time and when I moved to using generic collections in Java something just felt wrong. How was I to ensure my collections contained the correct types?

But you know what? Much to my surprise over the years, I've never really had a problem. I can't even remember the last time (if ever) I had a class-cast exception from accidentally adding the wrong type of object to a collection.

Which one of these would you rather?

The generic collections approach:

Collection customers = ...;
for (Iterator i = customers.iterator(); i.hasNext(); ) {
    doSomething((Customer) i.next());
}

Versus the custom type-safe collection:

public class CustomerCollection extends AbstractCollection {
    private final Collection _customers = new HashSet();

    public boolean add(Object object) {
        return addCustomer((Customer) object);
    }

    public boolean addCustomer(Customer customer) {
        return _customers.add(customer);
    }

    public int size() {
        return _customers.size();
    }

    public Iterator iterator() {
        return customerIterator();
    }

    public CustomerIterator customerIterator() {
        return new CustomerIterator(_customers.iterator());
    }

    public final class CustomerIterator implements Iterator {
        private final Iterator _iterator;

        private CustomerIterator(Iterator iterator) {
            _iterator = iterator;
        }

        public void remove() {
            _iterator.remove();
        }

        public boolean hasNext() {
            return _iterator.hasNext();
        }

        public Object next() {
            return nextCustomer();
        }

        public Customer nextCustomer() {
            return (Customer) _iterator.next();
        }
    }
}

CustomerCollection customers = ...;
for (CustomerIterator i = customers.customerIterator(); i.hasNext(); ) {
    doSomething(i.nextCustomer());
}

Not so bad you say? Well try doing this for every type for which you need to hold collections. Then try implement List or Set instead of the basic Collection. Don't even think about what it takes to implement Map. I admit, you might end up re-factoring some of this into a generic base class. You could even write one without implementing any of the collection interfaces. But then, why bother?

Sure, they might have save me a few keystrokes here and there but because most people (as I have done in my example) create their type-safe collections with names like getCustomer(), etc. it saves me 2 key-strokes over using a simple cast like (Customer). In fact, in the example given, I actually ended up with more key-strokes!

"But it's not about keystrokes, it's about type-safety" I hear you exclaim. Well yes, you may be right. But as I mentioned earlier, I don't recall this ever being a problem on any projects I've worked on. Oh, how that I think about it, there may have been one project but I'm pretty sure we simply shot the offending developer for being such an imbecile ;-)

I'm currently enduring the pain of working on a project where the consensus was that we should have type-safe collections. I seem to spend half my day implementing these instead of letting IntelliJ and Eclipse do a fine job of adding the casts in for me.

And so it is that I eagerly await the release of JDK 1.5 and language supported type-safe collections in the hope that it'll once and for all stop people writing these useless custom implementations. Egads!

December 26, 2003

Be Assertive

Listen to this articleListen to this article

I recently discovered a bug in an Ant task I had written a while back. A customer was running the code and it barfed with an IllegalStateException telling them proudly that the "formatterType cannot be null". Nothing special about that I suppose. A NPE would have done much the same thing. The only difference is that the code is obfuscated. That means the stack trace is totally useless. Not only that, but they were running an older version of the software which would have meant I would have had to check out that particlar version from CVS, build it and see if I could work out what was going on.

As it turned out, There were only two places in the code that performed a null pointer check with this particular message and only one of them is called from the Ant task. A bit of detective work later (like 5 mins tops) and I had a failing unit test written and running. The fix was one line. Actually half a line as it required assigning a default value to an instance variable in the declaration :-).

I program defensively. I check parameters for null pointers, I assert that objects are in the correct state at the start of the method etc. I've found I catch strange bugs much, much earlier than if I simply wait for the NPE. I also have a preference for immutable objects, which substantially reduces the set of things I need to check for. I've had countless debates with, mostly junior, developers who believe that it's better just to wait for the NPE. But fundamentally, I put assertions into my code so that out in the field my software fails in predictable ways. Ways that will ultimately help me to identify the nature and cause of a problem as easily as possible.

I even have an IntelliJ macro setup so that it's as painless as possible to add a check to my code. And just to be sure, James Ross and I even wrote a custom checkstyle check to ensure that an object reference is always checked for null before being used.

There are also a number of libraries around such as iContract and jContractor, that go way beyond simple assertions and allow you to add Design by Contract conditions to your code via javadoc comments and byte-code modification, special methods, macros that a pre-processor inlines, etc. Though I've never used them, I'd be interested in comments from anyone that has.

The thing is, I've never used the assert statement in java. That doesn't mean I don't believe in assertions, clearly. I've just never used the built-in support. I've never liked the fact that you can turn them off. To me, this defeats the reason for having them there in the first place. In fact the JDK assertions (at least in 1.4) have to be explicitly turned on. I'm not so much interested in catching NPE's etc in development as preventing really bad things happing in production so to me, it seems rather pointless to turn then off.

Instead, I use a custom Assert class that works in any JDK and can't be turned off.

public final class Assert {
    private Assert() {
       throw new UnsupportedOperationException("Constructor should not be called");
    }

    public static void isTrue(boolean condition, String message) throws IllegalStateException {
        if (!condition) {
            fail(message);
        }
    }

    public static void fail(String message) throws IllegalStateException {
        throw new IllegalStateException(message);
    }
}

(This is one of those times where I feel it's just fine to have a bunch of static methods. Imagine butchering your code to have an Assert object passed into the constructor of every class I ever created? YUK! ;-) All you AOP weenies get back in your box before things get ugly!)

I also noticed commons-lang has a Validate class that provides the same functionality (and then some). Though, again, I've never used it myself.

I can think of one possible reason why I might want to turn off not only an AssertionError being thrown but the condition check itself. If you're using asserts for checks such as "when the method ends, there should be at most 2 address records for the customer". This may well be an expensive operation that you don't want performed everytime in production but I don't tend to check these sorts of things. Now I'm thinking maybe I should? Or is that what my unit tests are for? But then usng asserts, I could turn them on in production if I needed to catch some bug I was having trouble replicating. Having said that of course, if I had a sufficient test suite, I bet I could find the bug just as easily without resorting to debugging in production. Hmmmm

December 25, 2003

Best Practices

Listen to this articleListen to this article

I happened upon this post on the artima web site which reminded me that I had been wanting to rant a little about best practices for a while.

It has always seemed to me that so called "industry best practices" are really only ever identified at the end of a cycle of innovation. Or in other words, when many in the industry have moved on to developing "better" practices. My observation has been that companies striving to adhere to "best practices" are often at least 12-18 months behind the leaders.

Some (read large, conservative, glacial, etc.) companies take so long to adopt advances in technologies and methodologies, etc. that by the time they do, they're really using legacy* practices. They are highly risk averse. They can't, won't or don't employ talented developers. Instead they hire an army of over-paid whiteboard architects who couldn't build a software system if they tried. These whitebaord architects, with little or no understanding of what really goes on their own industry, need to protect their backsides by showing little or no innovation by promoting whatever methodolgy sees most of a projects time and budget justifying their employment and ensuring there is always someone else to blame if/when something goes wrong.

Now, don't misunderstand me. I'm, in no way suggesting you jump on the next AOP, IoC, whatever wagon that rolls into town. But don't be fooled that simply automating manual processes or creating a web site (inter-, intra- or -extranet) will suddenly make your business more efficient. We should be striving to deliver high-quality, adaptable systems that allow the business to realise competitive advantage as early as possible.

* For clarification, I'll define legacy to mean anything that clearly doesn't work to all but the people who try so hard to believe that it does not least because their jobs probably depend upon it. A kind of managed failure. As a reader suggests, if it works, it's not legacy.

December 23, 2003

I'd like to coin a phrase...

Listen to this articleListen to this article

... for software that bears not the hallmarks of great craftsmanship so much as lovingly "hand crufted code" ;-)

Testing with factories

Listen to this articleListen to this article

A long time colleage of mine asked me yesterday about IoC. After explaining about constructors, etc. we then discussed factories. He understood the way you would pass a single instance of say a widget to an object via the constructor, but what about something more complex that doesn't know which widget it wants or needs multiple widgets. Enter the factory.

Factories are really no different from other java objects that require some kind of lookup mechanism to find such as, JDBC connections, JNDI contexts, etc. One of the most common ways to implement factories to facilitate runtime lookup is the so called abstract static factory "pattern". (I used the term pattern simply because others have. In general I find most people abuse the use of the word, but that's a rant for another time).

For those not familiar with abstract static factory, the general idea is you create an abstract base class with a static method, say newInstance() or getInstance() for example, that returns the concrete implementation of the factory and an abstract method, say createWidget() that the concrete class implements. Typically, the concrete class is determined at runtime by using something as simple as a system property or something a little more sophisticated (ala META-INF/services). If you've ever used JAXP, you've been using one without possibly realising it.

public abstract class WidgetFactory {
    public static final WidgetFactory newInstance() {
        try {
            return Class.forName(System.getProperty(WidgetFactory.class.getName()).newInstance();
        } catch (...) {
            throw new IllegalStateException("Can't instantiate concrete factory: " + e.getMessage());
        }
    }

    public abstract Widget createWidget();
}

public final class WidgetFactoryImpl extends WidgetFactory {
    public Widget createWidget() {
        return new WidgetImpl();
    }
}

public final class Window {
    public Window() {
        add(WidgetFactory.newInstance().createWidget());

        ...
    }

    ...
}

I will usually have to set a system property to tell the abstract factory which concrete implementation to use. Apart from the fact that this destroys my ability to run multiple tests in parallel (system properties are global!), you could also think of it as a kind of violation of encapsulation - my test class has to know how the abstract factory is implemented so that I can tell it to return my mock factory instead.

public void testSomething() {
    System.setProperty(WidgetFactory.class.getName(), MockWidgetFactory.class.getName());

    Window window = new Window();

    ...
}

So anyway, given my love of TDD which seems to lead me to pass implementations of interfaces into constructors (ala IoC), I have a dislike of most things static. Even the abstract static factory.

Instead, I prefer to have the factory defined by an interface. Then pass an instance of the interface to the class that depends on the factory (ie no more newInstance()). In my test this can be a mock implementation, and at runtime this can be configured in a number of ways to pass a real implementation.

public interface WidgetFactory {
    public Widget createWidget();
}

public final class WidgetFactoryImpl implements WidgetFactory {
    public Widget createWidget() {
        return new WidgetImpl();
    }
}

public final class Window {
    public Window(WidgetFactory factory) {
        add(factory.createWidget());

        ...
    }

    ...
}

public void testSomething() {
    Window window = new Window(new MockWidgetFactory());

    ...
}

Sometimes this is difficult to achieve, especially when you have to use a 3rd-party API that only has an abstract static factory (such as JAXP). In this case, you really have a few possibilities:

  • Call newInstance() externally and pass the resulting concrete factory into the constructor. At least this way, you should be able to implement some kind of mock implementation, even if that means extending the abstract factory;
  • In the case of sframeworks that force you to have a default constructor, consider a hybrid where your objects have both a constructor that accepts an instance of a factory for your own use, and a default constructor that falls back on some kind of lookup mechanism (such as abstract static factory) and simply passes the factory instance to the other constructor; or
  • In the case of struts, as James Ross has pointed out, you can hang the factories out of the session or the application context and let struts set them for you; or lastly;
  • Continue using the factory ASIS from within the class. In the case of JAXP I can't see a big problem with this (one hopes that it is already fully tested!);

Naturally, I have a preference for the first approach if I can get away with it as it makes my life much simpler when it comes time to test and debug. No more flipping system properties, tests that can be run independently and in parallel, etc.

I can think of reasons for using the last method that are mainly to do with resource issues like "but I don't want an instance of the factory lying around if I don't need it. If that really is going to cause you resource issues (which I very much doubt), then at least wrap the factory in a class that lazily creates a factory for you.

December 14, 2003

Inversion of Control

Listen to this articleListen to this article

"I was expecting a paradigm shift and all I got was a lousy constructor!"

Perryn Fowler has asked me how would we use the Clock? How do we create one for production? The Inversion of Control (IoC) fraternity frown upon factories so what are we to do?

Luckily, software developed using TDD tends to lend itself to IoC.

This example conforms just fine with so called "Type-3" IoC which is based on passing dependencies via constructors. It's a very simplistic example nonetheless. For more complex systems, you may want to check out IoC containers such as PicoContainer et. al. which seem to be gaining in popularity. And for good reason.

These containers allow you to easily configure components and the dependencies between them. Although I must admit that I'm not a fan of the hype as some people have been building systems like this for a while now. The up-side of course is that others will hopefully feel more comfortable looking into it as an alternative now that it has a snazzy name and the obligatory TLA :-)

Once you get your head around it, it's pretty easy to see why people love the concept of IoC containers so much. In some ways it's not that much different to plugins but it does lend itself to other cool stuff, like decorating and "passivating". No more JNDI lookups, no more creating endless factories with staic methods. But as I said it can be hard to see at first how that works.

So here is the simplest example I could think of and whip up in 20mins. It displays a panel into which you can enter a duration to wait (in milliseconds) and a message to display once the time has elapsed.

It hopefully demonstrates how we can now use Alarms knowing they are fully tested and how we don't need a static factory to create anything.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main extends JFrame {
    private final JTextField _durationMillisField = new JTextField("3000");
    private final JTextField _messageField = new JTextField("Message!");
    private final JButton _setButton = new JButton("Set");
    private final Clock _clock;

    public Main(Clock clock) throws HeadlessException {
        if (clock == null) {
            throw new IllegalArgumentException("clock can't be null");
        }
        _clock = clock;

        getContentPane().setLayout(new GridLayout());
        getContentPane().add(_durationMillisField);
        getContentPane().add(_messageField);
        getContentPane().add(_setButton);

        _setButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                setClicked();
            }
        });

        setSize(300, 50);
    }

    private void setClicked() {
        int durationMillis = new Integer(_durationMillisField.getText()).intValue();

        Popup popup = new Popup(_messageField.getText());

        Alarm alarm = new Alarm(popup, _clock.getCurrentTimeMillis() + durationMillis, _clock);

        new Thread(alarm).start();
    }

    private class Popup implements Runnable {
        private final String _message;

        public Popup(String message) {
            if (message == null) {
                throw new IllegalArgumentException("message can't be null");
            }
            _message = message;
        }

        public void run() {
            JOptionPane.showMessageDialog(Main.this, _message);
        }
    }

    public static void main(String[] args) {
        new Main(new SystemClock()).show();
    }
}

Nothing too complex here. It doesn't go into testing GUIs (a topic for a book perhaps?) but as you can see, it would be possible to break down even this example into smaller chunks for testing. But really, the only thing the JFrame does is convert from screen values to primitives in order to create Alarms.

(As an aside, my original example had a Scheduler that created Alarms and setthem running in a Thread but again I thought I'd ke it as simple as I could so I simply put the code into Main.)

In some ways it seems almost trivial really. But if you can imagine a whole system done this way it's a pretty cool way to build apps. In a bizzarre way, it's kind of like rule based systems such as CLIPS or JESS only intead of delcarative rules that magically get evaluated, in this case, the dependencies are declarative and are magically resolved at run time.

Take a look at the other examples on the net and drop me a line if you want me to put together a more complex example using say PicoConatiner or NanoContainer.

What are your intentions?

Listen to this articleListen to this article

Allow me to vent for just a minute. I promise it won't take long...

In an effort to improve the amount of Javadoc in the source base, the current project I'm working on has been set up (not by me I might add) to use checkstyle to enforce Javadoc standards.

Following on from why javabeans are evil I have to say that enforcing Javadoc on getters and setters (that's accessors and mutators for all you Java Certified Developers out there :-P) is one of the most pointless things I've ever seen.

It takes me about 10 seconds to use IntelliJ (or eclipse for that matter) to generate all the getters and setters for the attributes on my DTOs. It then takes me ten minutes to either write the JavaDoc by hand. So I try using the auto generated javadoc only to find that it takes almost as long to change all the generated Obtains the value of paymentDate to Obtains the value of the payment date.

In fact it occurs to me that if my IDE can work out what to generate as javadoc, surely I can work out what the code is doing simply by looking at it?

I've always been a fan of commenting code. I guess it comes from my assembler programming days. I must admit I write fewer and fewer comments these days as my programming style has changed to be more "self-documenting". No matter what though, if you are going to write comments, it's important that you document the intent and not the implementation. How many times have I seen this:

++i;                          // Increment the current index
collection.add(values[i]);    // Add the value at the current index to the collection

This serves no purpose other than to satisfy the good-old comment/source-code ratio checker :-). Even worse, it adds nothing to my understanding of the code (ie intent) and IMHO adds significantly to the signal/noise ratio.

Most javadoc I see follows along similar lines. When 50% of the code is comments, kindly informing me that the getCustomer() method Gets the customer, etc. I can't help but wonder what the hell we've been spending our time doing.

What's worse, as with most kinds of heavy documentation, the comments rapidly become out of date as we constantly refactor the code, rename classes, attributes, etc.

Hmmm...I'm no language expert (as is evidenced by my ramblings on this site) but I wonder if it's possible to analyse the comments and determine if they're documenting intent or implementation detail?

In any event, as a start, do me a favour and don't enforce Javadoc on getters and setters. I'll meet you half way and try to get used to putting opening braces on a new line :-)

Domain Driven Design

Listen to this articleListen to this article

I spent many years writing software that was essentially procedural in nature with transaction scripts accessing a database through very simple active records. Since I've come to appreciate the benefits of a rich domain model I've wished I had the ability to communicate this to others.

So I was excited when I heard about the book Domain Driven Design.

It's nicely written. A good mix of code, diagrams, anocdotes and I particularly like the transcripts of conversations from actual modelling and design sessions. Lots of examples, rules of thumb and hints and tips here and there. It reminds me of Pragmatic Programmer in the way it reads.

Points I've particularly liked:

  • Model-driven design he says "discards the dichotomy of analysis model and design to search out a single model that serves both purposes." Something I've always felt since reading Analysis Patterns. As the author points out, this is very hard to do but well worth the effort.
  • The good old manufacturing metaphor where highly skilled engineers design and less skilled laborers assemble the products has "messed up a lot of projects for one simple reason--software development is all design." All right! Rock on! I'm printing that out in 70pt font and sticking it up on the wall of my favourite enterprise architects office!
  • "If an unsophisticated team with a simple project decides to try a MODEL-DRIVEN DESIGN with LAYERED ARCHITECTURE, it will face a difficult learning curve." I've recently pondered this as I've struggled with bringing teams of developers up to speed with these concepts. I've wondered whether I may be making matters worse before they, hopefully, get better.

Things I've disliked:

  • As Doug points out in his review, I too was a bit surprised by the "Manager" classes. Seems to defeat the whole purpose of rich domain models but as I haven't finished yet and, the author promises to address this later in the book (fingers crossed) I've chosen to ignore it so far.
  • The book is rather verbose I'm sad to say. I got into the first section and started to stall! It was very hard to get motivated to read the rest of the book.

All in all not a bade book. Someone definitely needed to write about it but as I mentioned, it was a little verbose for my liking. But I did finish it and I'd have to say that it was probably worth it.

December 13, 2003

Don't blame the brace

Listen to this articleListen to this article

Everyone remember this:

int main(int argc, char *argv[])
    {
        return 0;
    }

The C programming language is the the ancestor of Java that no one likes to talk about anymore. One of the overriding imperitives when developing the syntax of the language was ease of compilation. Curly braces make it easy for a parser to work out where blocks of code start and end. So naturally, we humans realised we could use them for the same purpose. Only we also worked out, smart little things that we are, that code is much easier to read if nested blocks are indented. This way the blocks stand out even more.

(As an aside, languages like Python use this indenting to delineate blocks of code which is kinda cool in my book but certainly not to everyones taste).

Anyway, next thing you know, the C language takes off. Developers used curly braces on new lines and indenting to make their code more readable. You could easily match up start and end blocks, you could see the nesting. Ooh it was a happy time for all. Sure made a change from all that assembler code right? Great mountains of code are produced. Functions from tens to even hundreds of lines long, containing levels so deep that, once again, it became hard to tell where blocks of code started and end.

Enter the end-of-block-comment! "Of course!" exclaimed the developers, "lets mark the end of each block with a comment to indicate what to look for when searching for the start. If it's a while loop we'll add /* while */ at the end. If it was a for, we'd finish with a /* for */ , etc. What a sensible idea" they chuffed.

Years later, we C programmers ventured forth into the brave new world of C++ and sometime thereafter, into Java, bringing with us all our accumulated knowledge and wisdom.

When I wrote Simian one of the first things I noticed was that removing curly braces from the input stream improved the overall effectiveness of the matching. Why? Because by removing the curly braces, I reduce the signal/noise ratio. Yup, curly braces are noise. They started off as a neat way of simplifying parsing and still add little value over and above that.

"But, but but..." I hear you complain loudly. "What about all the examples you've just given. Surely that counts for something?"

Sure. If you have methods that are hundreds of lines long. If you have blocks of code nested 3, 4 even 5 or more levels deep. If you have boolean expressions containing dozens of conditions, then you know what? I might just have to agree with you.

But I don't! I have methods with an average length of no more than probably 15 lines with an upper bound (enforced by checkstyle) of 30. I'm talking executable statements here not simply EOL characters.

Make your code more readable by simplifying the code! Break out those conditionals. Break out those nested for loops. Stop nesting try-catch-finally blocks. Break up those ugly switch statements and turn them all into private methods. Make them all static final if you're worried about performance (not that it buys you much these days). The fact is that compilers can do wonders with inlining of private methods these days. Compilers are much smarter now than when Mr. Kernighan and Mr. Ritchie were playing around with their lovely new C language compiler.

Importantly, I believe the usual arguments over whether one way is esthetically more or less pleasing than another are a waste of time. It's not a democracy but it is a benevolant dictatoriship so if you like it that way let's all agree and get over it. Just please stop using the curly brace as an excuse to write crappy code.

December 11, 2003

Question for all you blogging gurus

Listen to this articleListen to this article

I just received a message from a reader:

"Hey I just wanted to let you know I really enjoy your blog but I've been getting lots of duplicate copies of your posts in my RSS reader (Newsgator), I don't know if this is because you repeatedly modify your posts? And now I've gotten another copy of all your posts back to Nov 28 so I have to find them all to mark them as read. So I unsubscribed (But I should still receive your posts from javablogs.com I guess if it is still in operation :)."

I had no idea this would happen. Doh! Some technologist I am LOL.

So to my question: is there a way to not have it behave this way? Or should I just stop editing my blog? Hehehe. I continually update it to correct spelling mistakes and typos in code examples, etc. So that seems like a rather crappy solution. Or maybe I should just move to a wiki with an RSS feed? Any idea?

I'd hate to think how many others are frustrated with seeing the same stuff appearing over and over again.

And you all rock! I hope this works but the solution seems very simple:

"It's a stupid feature of newsgator that is on by default. Whenever a blog entry is modifed it's sent to the user as a new blog entry. It is easily turned off in the options, but I believe the user needs to configure this for each rss feed."

It's an obsession

Listen to this articleListen to this article

As I noted earlier, Perryn Fowler spotted the "deliberate" bug in the clock code. These two entries prompted some interesting commentary suggesting (possibly quite rightly) that I've been obsessing about unit tests.

While I think the points raised are valid, I'm compelled to note that my obsession lies with improving code quality and Test Driven Development (TDD) in general and not specifically with unit testing.

My focus recently has been on unit testing because I disagree with the idea that developers focus too much on unit tests. My experience is that developers are more than capable of writing great swags of integration and functional tests over poorly constructed, hard to understand and hard to maintain code. Not to mention that the tests are written as an after thought, are often difficult to automate and take countless hours to run even when they are automated.

I would never claim that one should only write unit tests. Rather, I would simply ask that you start with a test. Some have noted that TDD takes us back to the "good old days" of top down development :-)

FWIW, I write significant numbers of integration tests, often (though not always) before I've written the corresponding unit tests. Why? Because I need to test my assumptions about the behaviour of various layers, libraries etc. on which my code will depend. Then when I've verified my assumptions (probably learning much more than I had anticipated along the way) I am happy to ignore those layers for as long as possible.

And there is no doubting that there is an absolute, cannot do without, requirement for a comprehensive functional test suite. Frameworks such as Fit, jWebFit (part of the jWebUnit package) and Fitnesse are interesting in that they hold the promise of writing functional tests before writing the code! But as yet, I've no practical experience worthy of note using them. I assure you that when I do, I'll let you know :-)

Although I would never recommend mocking infrastructure, people have used service stubs since the dawn of software development. There is no denying that these are vital when access to back-end systems is not always guranteed. In keeping with the fractal nature of software, I don't see there is a difference between stubbing a mainframe application for testing business logic, and stubbing and application server for testing presentation logic.

None of this, however, in anwyay explains my interest in (obsession with?) TDD.

My strongly held belief is that TDD isn't actually about testing. For one, it's about documenting requirements and letting those requirements drive the design of the application. And importantly, the observation of many that easily testable code is designed well, is easier to understand and easier to maintain.

December 10, 2003

Why EasyMock Rocks

Listen to this articleListen to this article

My favourite mock objects library is EasyMock. IMHO, if you need much else for mocking stuff on a new project at least, you're mocking (read testing) the wrong thing.

It's uses Javas built-in dynamic proxies, meaning you can mock out anything that is defined by an interface.

I was helping someone to write some tests recently and explining how to use the library when she noted that "it's like a macro recorder." I had not thought of it like this but I guess she's right.

The idea is you create the mock object and then call it in exactly the way you expect the class under test to call it. The cool thing about this is that you get to use the same interface as the class under test. You setup expected method parameters, return values and even exceptions. Then when you're done setting it up, you call the class under test and EasyMock handles the rest.

As an example, I thought I'd take the clock code and write a test. (P.S. Anyone spot the "deliberate" mistake? Perryn Fowler did.)

public void testThreadInterruptedWithTimeExpiredShouldNotSleep() {
    // Create the mock clock
    MockControl clockControl = MockControl.createStrictControl(Clock.class);
    Clock clock = (Clock) clockControl.getMock();

    // Create the mock task
    MockControl taskControl = MockControl.createStrictControl(Runnable.class);
    Runnable task = (Runnable) taskControl.getMock();

    // Setup an alarm to go off at time=10
    Alarm alarm = new Alarm(task, 10, clock);

    // When run, the alarm should check the current time.
    // We'll tell it that the time=1
    clock.getCurrentTimeMillis();
    clockControl.setReturnValue(1);

    // This will cause the alarm to calculate the sleep time.
    // We pretend the thread was interrupted suffiently that the alarm
    // time has now expired, time=11, which should cause the task to be run
    // immediately.
    clock.getCurrentTimeMillis();
    clockControl.setReturnValue(11);

    // We want the task to be run once, and once only!
    task.run();

    // Tell the controls we're ready to rock'n'roll
    clockControl.replay();
    taskControl.replay();

    // And away we go...
    alarm.run();

    // Final check to ensure no expected methods are left outstanding
    clockControl.verify();
    taskControl.verify();
}

Running this test should demonstrate the bug just nicely, resulting in the following exception (that'll teach you to write the code without even running it!):

junit.framework.AssertionFailedError:
  Unexpected method call sleep(-1):
    sleep(-1): expected: 0, actual: 1
        at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:41)
        at $Proxy0.sleep(Unknown Source)
        at Alarm.waitForAlarmTime(Alarm.java:30)
        ...

How easy is that! You'll note that at least 50% of the "code" is actually comments I added for understanding, making it seem a lot longer than it really is.

Some traps for young players though:

  • Don't forget to call replay() for each control prior to invoking the class under test. If you do forget, you'll end up java.lang.IllegalStateException: missing behavior definition for last method call on the mock;
  • Don't forget to call setReturnValue() or setThrowable() on the control after calling a method on the mock object. Again you'll end up with java.lang.IllegalStateException: missing behavior definition for last method call on the mock; and;
  • It's a good idea to call verify() on each control at the end of the test just to be sure.

About the only feature I can think of that I'd like added would be for a single control to handle multiple interfaces. That way I can have the ordering of calls across multiple interfaces checked as well. It should be relatively simple as dynamic proxies already support this. Without this feature, there's no real way to tell if the tasks run() method was called at the correct point in time. I draw the line at creating a dummy interface that extends both Clock and Runnable purely for testing ;-).

December 09, 2003

Analysis patterns

Listen to this articleListen to this article

When I first moved over to the cool new world of OO, I just loved the fact that, especially in C++, I could use inheritence to do so many things. I could just create yet another sublcass, override some method/s and bingo problem solved. What I didn't realise was that I was creating an enormouse mess of brittle, crufty, hard to maintain code. Personally, C++ multiple inheritence didn't help! But let's not go there just now shall we :)

So, for a simple problem with some very basic requirements:

  • We have bank accounts
  • We can transfer money from (debit) at most one account
  • We have 2 types of transfers
  • Single funds transfers allow crediting to one account
  • Multi-funds transfers allow, you guessed it, multiple credit accounts

Now, how would you have modelled this? There are of course no right or wrong answers but I'm curious to hear your thoughts.

You see, the most common solution I come across has two sub-classes, one for each type of transfer. One allowing a single credit and the other allowing a collection of credits.

As you've probably guessed however, this isn't my preferred solution. I'd rather see a single class for a transfer with a collection of credits and some kind of constraint class that holds "rules" regarding minimum and maximum numbers of credit accounts.

I'd say the most influential books I've ever read to do with software developement, in the order I read them, were:

The last is probably not as well known as the first two but, quite aside from the patterns themselves, it fundamentally changed the way I model problems. For one, I stopped creating ridiculously deep class heirarchies to solve every problem I came across.

It's been many years now since I read Analysis Patterns but I've had cause to refer back to it recently in group modelling sessions. If you've not read it I highly recommend that you do.

December 08, 2003

Static imports

Listen to this articleListen to this article

I have no idea which crack smoking monkeys thought this was a good idea. Talk about clash of the namespaces. Has no one ever tried to use java.util.Date and java.sql.Date in the same class? But while we're at it, can we have pointer arithmetic back as well? Ooo...ooo...how about C#-like properties. Yeah! You know, I'd really like to be able to embed java-byte code directly into my source using some kind of assembler-like syntax too. Imagine how cool that would be!

I take comfort in the fact that large organisations (for whom I'm most concerned) are so slow to move, their developers won't see JDK 1.5 for at least the next 3 years hehehe.

Oh well. I can see a new checkstyle plugin coming real soon.

Price / performance at what cost?

Listen to this articleListen to this article

Whenever I find myself participating in the "I love IntelliJ" versus "I love Eclipse" debate, the old "Ya can't beat price/performance" argument is rolled out faster than you can say "perspectives? what the...?". So let's do the math:

price / performance = 0 / anything = 0

or perhaps:

performance / price = anything / 0 = undefined

But seriously, Eclipse would be a great platform if I could just bend my head around to thinking the way Mr. Gamma wants me to.

It's that old mental model thing. I admit I had the same problem when I first starting using IDEA. It really comes down to what you're used to. And the fact that IDEA somehow knows what I want to do hehehe

I just thank my lucky stars I can use Eclipse 3.0. I'm even happier I don't have to use WSAD. Sheesh at AU$10,000 / seat? How many games of golf did the IBM rep have to lose to convince the "Architects" that was a good purchase? 'nuff said!

So right now, my performance is approaching new lows as I reprogramme my tiny wee brain. But I'm getting there. Though, I still sneak home for a puff of the IDEA cigar every night just to feel that rush of endorphins again :-)

December 07, 2003

Crossing the road

Listen to this articleListen to this article

When it comes to crossing the road, I'm just about as daredevil as the next person. I cross against the lights. I J-walk. You name it. Except when I see young children.

I approach an intersection looking both ways for oncoming traffic, about to cross against the lights when, out of the corner of my eye, I realise there are young children standing patiently for the lights to change.

It's as if someone has erected an invisible wall. I stop dead in my tracks. I'm very thingy about it. I figure I'm old enough and ugly enough to know what I'm getting into but I don't want to give these young kids a bad example. They're not really old enough or experienced enough to know what's safe or dangerous nor the neccessary motor skills even if they did. It's almost like I feel a duty of care to towards them. I think as software developers we have similar resposibilities.

I consider myself to be a developer of average competence. I've been around the block a few times so I've made countless mistakes and, hopefully, learned from them. I'm pretty anal when it comes to certain things (as you've no doubt realised by now). But when I'm doing my own mini projects, sometimes I relax a little. Maybe I write some code that doesn't have tests (howls from the crowd!). Maybe I hard-code a bunch of stuff I wouldn't otherwise. The thing is I feel I've done enought to know when I can get away with it and when it's just too darn important to overlook.

Sometimes mentoring and coaching can be like crossing the road. If I were by myself, I'd be quite happy to weave between the cars. But when there are kids around, maybe it's better to sacrifice some speed for a little more safety?

As my good friend Damian Guy pointed out to me "that is why I like pairing. It is too easy to slacken off otherwise."

December 06, 2003

When is a clock not a clock?

Listen to this articleListen to this article

When it's a mock.

It's a common problem. You need to test behaviour of an application based on the system clock. Say some event that is triggered every n minutes, or at a certain time, etc.

Allow me to go nuts with some code examples for a change :-)

The most common solution to the problem is to do something like this:

public class Task implements Runnable {
    private final long _alarmTimeMillis;

    public Task(long alarmTimeMillis) {
        _alarmTimeMillis = alarmTimeMillis;
    }

    public void run() {
        waitForAlarmTime();
        doSomething();
    }

    private void waitForAlarmTime() {
        while (System.currentTimeMillis() < _alarmTimeMillis) {
            try {
                Thread.sleep(_alarmTimeMillis - System.currentTimeMillis());
            } catch (InterruptedException e) {
                // Ignore it
            }
        }
    }

    private void doSomething() {
        ...
    }
}

This raises two questions in my mind: Firstly, should the action taken by the task really depend this closely on the scheduling? And secondly, how are we going to test it?

Let's deal with the easy problem first. Let's create a class called say, Alarm that looks something like this:

public class Alarm implements Runnable {
    private final Runnable _task;
    private final long _alarmTimeMillis;

    public Alarm(Runnable task, long alarmTimeMillis) {
        if (task == null) {
            throw new IllegalArgumentException("task can't be null");
        }
        _task = task;
        _alarmTimeMillis = alarmTimeMillis;
    }

    public void run() {
        waitForAlarmTime();
        _task.run();
    }

    private void waitForAlarmTime() {
        while (System.currentTimeMillis() < _alarmTimeMillis) {
            try {
                Thread.sleep(_alarmTimeMillis - System.currentTimeMillis());
            } catch (InterruptedException e) {
                // Ignore it
            }
        }
    }
}

Now this doesn't look much different really except for one very important thing: We've decouple the scheduling from the action. Alarm now depends on a Runnable (an interface) to actually get the work done. That means Alarm is responsible for one thing only. Namely, the scheduling of a task. This allows us to independently test the schduling component and the task itself.

Because Runnable is an interface, we can easily code up a test that creates an implementation of Runnable purely for testing. Ie. a mock object. And because the tasks are now independent, we can test their behaviour irrespective of when they are likely to be scheduled.

So far so good. But how does this all relate to the original title? Well when we go to code up our AlarmTest we encounter some grief due to the fact that Alarm is coupled to System.currentTimeMillis(), a static method over which we have no control and also to Thread.sleep() another static method over which we have no control!

The solution however is relatively simple: Let's help save the object by introducing our own abstraction of the system clock.

We'll make an interface and call it, strangely enough, Clock:

public interface Clock {
    public long getCurrentTimeMillis();

    public void sleep(long millis) throws InterruptedException;
}

Now we can re-write our Alarm like this:

public class Alarm implements Runnable {
    private final Runnable _task;
    private final long _alarmTimeMillis;
    private final Clock _clock;

    public Alarm(Runnable task, long alarmTimeMillis, Clock clock) {
        if (task == null) {
            throw new IllegalArgumentException("task can't be null");
        }
        _task = task;
        _alarmTimeMillis = alarmTimeMillis;
        if (clock == null) {
            throw new IllegalArgumentException("clock can't be null");
        }
        _clock = clock;
    }

    public void run() {
        waitForAlarmTime();
        _task.run();
    }

    private void waitForAlarmTime() {
        while (_clock.getCurrentTimeMillis() < _alarmTimeMillis) {
            try {
                _clock.sleep(_alarmTimeMillis - _clock.getCurrentTimeMillis());
            } catch (InterruptedException e) {
                // Ignore it
            }
        }
    }
}

This allows us to implement a SystemClock that simply delegates to the original methods we called. But importantly, we can also implement our own MockClock that returns whatever values we like for getCurrentTimeMillis() and does whatever we like (most likely nothing) for sleep().

Not only does this make it easier to test, but it also means we don't actually have to have our test wait for 3 hours just to see what happens. We can simply have our MockClock pretend to sleep for 3 hours.

We haven't tried to make our own Thread or subvert the System class or clock in anyway. We've taken control and not allowed ourselves to be dictated to by someone elses API.

There's still obviously some room for improvement here. We could make the Clock API possibly a little higher level, maybe? We could provide a ClockFactory if you don't like the idea of passing it into the constructor (ala IoC). But you hopefully get the gist.

Of course had we done this test-first, we would likely have arrived at this solution in the first place. But it does serve to illustrate the point that, IMHO, testability necessitates good OO design.

My stuff is too complex to test

Listen to this articleListen to this article

Boulderdash! Dealing with complexity is the essence of software engineering. I particularly liked the idea that software is fractal in nature as it is something I've always tried to communicate to others. The interactions between components in any layer (should) look the same as the interactions between layers. No matter what the level of abstraction. But I digress.

If you've managed to build a system that does the job but is too hard to test, then your system works by coincidence. Sure you may think you've deliberately implemented a solution in a particular way but the fact that it works is more dependent on probability than pure determinism.

If it seems too complex, first break the problem down into smaller, more manageable, chunks. Start solving the smaller problems. Then start re-factoring and abstracting based on common code, common solutions, etc. In this way, large systems become a complex arrangement of simple things.

Software that is designed well is testable. The corollary to this is that software that is not testable is designed poorly. A focus on testability results in software that is well designed.

Can you guess what the next three letter acronym is likely to be?

If you guessed TDD, you guessed right!

December 04, 2003

Help save the object

Listen to this articleListen to this article

I have an innate dislike of the so called static helper class.

If you've not seen one of these, you are very lucky indeed! It's a class that contains entirely static methods that usually perform convenience functions such as data conversions, formatting, resource management, you name it.

If you've come from a C or VB background, it's probably a natural way to bring back that warm fuzzy feeling to the otherwise scary world of OO.

The problem is, static classes are difficult to decorate (yes, again, I know we now have AOP frameworks) and importantly, they're not pluggable (as in Strategy) which means you can't mock them out for testing!

Quite often, the behaviour would be more appropriately placed in the class on which the processing is being performed instead of exposing the internals of the class just to perform a caclulation. If you do need to expose some of the internals, trun it around and use a Visitor. At the very least, turn the class into a Singleton and possibly even use a factory method of some kind. The java libraries have very few static classes. When they do (such as java.util.Collections) they're almost always some kind of factory.

So next time you're building a system, spare a few lines of code and help save the object. Better still, start practicing test-driven development and see how few of these things you end up with :-)

P.S. I've been accused of using too many acronyms before. This time I'm sure to be accused of using too many patterns. That's what patterns are for: communication. It saves me having to write a whole lot of code to explain what I mean. So get over it! :-)

Definition of insanity

Listen to this articleListen to this article

Ever noticed how some organisations persist with processes/people/tools that, on reflection, fail every time yet continue to justify their use with the promise of success "the next time"?

Is it too much to ask for competant people? If they aren't, we need to find new ones. If they lack experience, we need to educate them. Process+Monkeys is NOT the answer. Sure process is important but allow process improvement to flow upwards from the experience of developers, not downwards from the ideals of Architects. Capability is developed through real projects. Abstract frameworks and overpriced development tools are not the solution. And I don't know about you but it seems to me that more often than not, simply sending developers on courses can often be like paying someone to take time off to read a manual!

Maybe they believe that people don't matter? That process and tools will ultimately replace people and, therefore, we should simply employ substandard people and continue to improve the process and tools until they achieve this goal?

Better the devil you know?

Certainly it's been my experience that large consulting firms and software vendors draw a (very) fine line between doing what's best for the customer and commercial imperitives such as expanding the account and selling more 'wares. Thankfully, I've never worked for a company that acted in this way but I am unfortunate enough to have beeen forced to work with them.

I've wondered recently if, in some perverse way, large organisations are ethically and morally obliged to employ substandard people. That way they can continue to make outrageous profits. I mean, imagine if they were actually efficient at doing business. Imagine how much money they'd make then. Hehehe.

All companies I've been doing work for recently definitely want to change. I just wonder how much inertia there is to overcome or if it's even possible.

Hopefully they'll realise they can't continue to repeat the same behaviour and somehow expect different results.

December 03, 2003

Aren't classes supposed to have both data and behaviour?

Listen to this articleListen to this article

A bit late off the mark but I only just found an old article on why getters and setters are evil. Combine this with my preference for immutable objects, and JavaBeans often become the devils work. It also fits in nicely with another article I read recently, Martin Fowlers AnemicDomainModel, in that both talk about the value of spending the time to put behaviour back on classes rather than having dumb data objects with essentially procedural functions (in the way I usually see entity and session beans used).

It's a strikingly difficult concept to grasp. I know I struggled with it for years. And I've found it even harder to convince others of since I did get it.

Here's a typical example I see quite often. Now this is only my opinion of course but instead of:

account.setStatus(AccountStatus.CLOSED);

I'd prefer to see this:

account.close();

Internally, the Account might simply look like:

public void close() {
    setStatus(AccountStatus.CLOSED);
}

But it might also do something more. In this trivial example, the benefits are not so obvious but, when the logic becomes more complex, the setStatus() method can become quite large and usually ends up with a switch statement that (hopefully) delegates to separate methods anyway. So why not just call the methods explicitly. After all, the AccountStatus class is really an implementation detail, albeit a common one.

Having said this, deciding where behaviour belongs is often quite difficult. I often find myself using Strategies and Composites instead of inheritence but I've also found this a difficult concept to communicate, with doubters usually exclaiming "But aren't classes supposed to have both data and behaviour?" :-)

December 02, 2003

It's not a democracy

Listen to this articleListen to this article

"Smart people don't always make smart decisions." -- anonymous

Ahh yes. The code review...

Why do some developers feel that adhereing to (largely) well accepted design practices and coding standards (anyones just have them!) somehow takes away their freedom of expression when they're quite happy to unwittingly limit themselves by way of poor design choices and down right rotten coding practices?

Do they feel they work in a commune or democracy? It's not. Shared ownership I have no problem with. But shared responsibility? Yeah right.

Set your standards, enforce them and be done with it I say. You wanna debate about it, sure, now lets stay back and re-factor the code so that it now adheres to the new standards! I've done it before. It's a lot of work. But you gotta admit the code was easy to extend and maintain.

Use Checkstyle, PMD, or similar tool that is extensible enough to add your own. These tools dont just check line lenghts anymore. They can be used for enforcing design patterns, looking for poor ot at least suspect coding practices. Almost anything really.

And make sure you have a code cop with Balls!

December 01, 2003

Adapter classes

Listen to this articleListen to this article

Since I ranted about abstract classes a couple of days ago I've read quite a number of other blogs that discuss interfaces versus abstract classes. Most of the discussion seems to be around the fact that adding a method to an interface is a pain because you need to add that method to any class that implements the interface. The solution in some cases (but definitely not all) is to have an "adapter" class that provides empty implementations of all methods. You can then extend this and override only the methods you need. For example:

public interface Foo {
    public void somethingHappened();
}

public class FooAdapter implements Foo {
    public void somethingHappened() {}
}

This can make a lot of sense if you're implementing some kind of listener/observer. But if the interface is required to return something as in:

public interface Foo {
    public int getSomething();
}

then what do we do? Return 0 for integers, null or "" for strings or throw UnsupportedOperationException?

Interestingly, if you don't recompile the implementing class and something attempts to call a method on the interface that you haven't implemented, the JVM will throw a NoSuchMethodError.

The one place where it might bite significantly is if/when you change a public interface in a public API. Once that API is published and used by third-parties, it becomes much harder to change for fear of breaking backwards-compatibility.

At any rate, these "adapter" classes aren't really abstract classes nor are they types. They are once again a convenience of the programming language. Ruby and smalltalk for example will, like the JVM, throw an exception if you attempt to call an unimplemented method on a class. The difference being that Java's strong typing forces you to deal with it up front.

So, putting pandora firmly back in her box, I don't see that any of this really goes against my original proposition that abstract classes are not in fact types.

Ahh crufty code

Listen to this articleListen to this article

Inspired by this blog entry I thought it was time to start blogging some of the crufty code that I come across from time to time and find highly amusing. Now having said that, let me say this: I've written a bunch of crufty code in my time (if we lived by my good friend Jon Eaves rules of life, I'd have been removed from the gene pool long ago). I'd say probably every 12 months or so I look back on stuff I thought was great at the time and whince. But I have to admit that some of these are just way too funny not to air. Feel free to email me or comment with your own. So here goes...

These are just plain broken and wrong:

String s = new String();

String s = new String("");

String s = new String().valueOf(someInt);

try {
    ...
} catch (RuntimeException e) {
    e.printStackTrace();
}

try {
    ...
} catch (Exception e) {
    if (e instanceof SomeException) {
        ...
    } else if (e instanceof AnotherException) {
        ...
    } else {
        throw e;
    }
}

if (aBoolean == true) {
    return true;
} else {
    return false;
}

Next, I can only assume the developers thought that finally was only run after a catch?

try {
    return someMethod();
} catch (...) {
    ...
} finally {
    return null;
}

Some lesser evils...

Instead of this:

Object[] objects = someCollection.toArray();
for (int i = 0; i < objects.length; i++) {
    ...
}

try:

for (Iterator iter = someCollection.iterator(); iter.hasNext(); ) {
    Object o = iter.next();
    ...
}

This is pretty anal but instead of this:

return new Boolean(aBoolean);

use either of these two:

return Boolean.valueOf(aBoolean);
return aBoolean ? Boolean.TRUE : Boolean.FALSE;

Shameless Plugs

Recommend me on Working With Rails

Simian (Similarity Analyser): Rapidly identifies duplication in Java, C#, C, C++, COBOL, Ruby, JSP, ASP, HTML, XML, SQL, Visual Basic source code and even plain text files.

Beginning Algorithms: A good understanding of algorithms, and the knowledge of when to apply them, is crucial to producing software that not only works correctly, but also performs efficiently.