avatarharuki zaemon

Inversion of Control

By

“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 static 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 20 minutes. 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 set them 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 bizarre way, it’s kind of like rule based systems such as CLIPS or JESS only instead of declarative 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 PicoContainer or NanoContainer.

What are your intentions?

By

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

By

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.

Don't blame the brace

By

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.

It's an obsession

By

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.

Question for all you blogging gurus

By

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 modified 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.

Why EasyMock Rocks

By

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 clockMockControl clockControl = MockControl.createStrictControl(Clock.class);
  Clock clock = (Clock) clockControl.getMock();

  // Create the mock taskMockControl 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=1clock.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 ;-).

Analysis patterns

By

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.

Price / performance at what cost?

By

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 :-)

Static imports

By

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.

Crossing the road

By

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.”

My stuff is too complex to test

By

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!

When is a clock not a clock?

By

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.

Help save the object

By

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!

It’s not so much of a problem if the behaviour is trivial such as performing a simple calculation. But when it involves reading from a database, putting messages on queues, etc. the situation becomes much worse. You end up setting up, configuraing and ultimately testing a lot more than you had anticipated.

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

By

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 competent 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 people far removed from the actual day-to-day work.

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 imperatives 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 been 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.

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

By

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:

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?” :-)

It's not a democracy

By

“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!

Adapter classes

By

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

By

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;

Don't panic, just cluster

By

I encountered a rather (un)amusing situation just recently. A project I was casually checking in on (just because I’m a nosey parker) had a unit test suite take 70 mins to run? “How many tests are there?” I ask. A couple of thousand I thought to myself? What if I told you 200!

Ok, so now that you’ve picked yourself up off the floor. You’re first thought would most likely be similar to mine: Aha! They’re hitting the database in their unit tests. Well how about this, they were hitting the database not just in every test, but setUp() and tearDown() are rebuilding the database by loading a schema and data from XML and re-populating it.

But not to fear, they’re on to it! They’re doing some work to speed up the tests. They’ve figured that if they create some extra database users they can run the tests in parallel!

Reminded me of another project I saw some time ago. The (web) application services around 2000 users concurrently. The application craps out so often that they decided to have a dozen or more servers all regularly saving session state to a database (read SLOOOOOW) so that the users would experience no perceptable loss of service.

So what do these have in common? In both cases, instead of looking at the design of the application. Instead of cleaning up the code and making it more reliable. Instead of reducing dependencies between layers. The answer was to cluster. I mean, why build better software when you can just throw more hardware and software licenses at the problem….KACHING$$$$$.

In the case of the testing, had it not ocurred to anyone not to hit the database at all? How can a unit test hit a database? Wouldn’t that classify, by definition, as an integration test?

As for the web app, it seems to me that had the code base been even remotely stable, the claims made by the application server even remotely accurate, add in a UPS and some RAID and the application would have been more stable than the average users internet connection.

Now don’t get me wrong, like all things there are times when you want to service 1000s of customer concurrently and you may well require lots of hardware. But the overriding factor must be to get the application right first. Then think about clustering. The old saying goes “A chain is only as stong as its weakest link.” If the application is broken in the first place, you will get ever diminishing returns my simply adding more and more servers.

It seems to me that in most cases, it’s rare to see a business application that warrants true (real-time session failover) clustering rather than just a simple server farm. I agree that a cluster and/or a server farm gives you the ability to to take a machine out for servicing, handle hardware failures, and to scale an application to handle more and more concurrent users. But it should not be used as a quick fix for poor software development.

Endulge me as I make a tenuous analogy with my martial arts training. Most martial arts teach that it’s not about strength. It’s about technique. Get your technique right first without resorting to brute force. Then when you can make that work, add in your natural strength and you will seriously kick butt.