Removing duplication from equality

A neat Java 5.0 snippet to remove duplication of standard equality checks between unrelated classes (eg: to stop Checkstyle complaining).

public abstract class Equality<T> {

    public boolean areEqual(T thisObj, Object thatObj) {
        if (thisObj == thatObj) {
            return true;
        }

        if (thatObj == null) {
            return false;
        }

        if (thisObj.getClass() != thatObj.getClass()) {
            return false;
        }

        return haveEqualFields(thisObj, (T)thatObj);
    }

    protected abstract boolean haveEqualFields(T thisObj, T thatObj);

}

Use it thus:

public class MyClass {

    private static final Equality<MyClass> EQUALITY = new Equality<MyClass>() {
        protected boolean haveEqualFields(MyClass thisObj, MyClass thatObj) {

            if (thisObj.foo == null) return thatObj.foo == null;
            return thisObj.foo.equals(thatObj.foo);

        }
    }

    private String foo;
    
    ...

    public boolean equals(Object obj) {
        return EQUALITY.equals(this, obj);
    }
}

You can of course define the equality in a separate class, have hierarchies of related equalities, etc.

Posted in Uncategorized | 4 Comments

The value of code

Value in stories

Generally, the features on a project should be those that will provide a value to the customer, for some definition of ‘value’. We can use the template

As a <role>
I want <something>
So that <I get some value or benefit>

to help us describe the stories which we use to prompt conversation about what that value is. The value doesn’t have to be monetary; it could mean a reduction in risk, an ease of maintenance, the ability to use a technology that will still be supported in five years’ time.

Value in code

A piece of code should provide value to the class, module, application, system etc. in which it resides. If a piece of value can be encapsulated into one block of code, chances are that it’ll be easier to read, maintain, find and delete, should that value ever become obsolete.

Here’s an example of something that I didn’t find any value in. I was coding John Conway’s Game of Life as a kata.

public void testShouldReturnTrueIfTheCellHasLife() {
    Grid grid = new Grid();
    grid.causeBirth(4, 8);
    assertTrue(grid.hasLife(4, 8));
}

This isn’t valuable, because I can easily make this pass with

public class Grid {
    ....

    public boolean hasLife() {
        return true;
    }
}

One way to get around this is to add another test:

public void testShouldReturnFalseIfTheCellHasNoLife() {
    Grid grid = new Grid();
    grid.causeBirth(4, 8);
    assertFalse(grid.hasLife(4, 2));
}

So now we have two tests, describing one benefit. I prefer this:

public void testShouldDetermineIfACellHasLife() {
    Grid grid = new Grid();
    grid.causeBirth(4, 8);
    assertTrue(grid.hasLife(4, 8));
    assertFalse(grid.hasLife(4, 2));
}

One block of code, one value which it provides. Using two tests for this would mean that the value was split; neither test has is truly valuable without the other.

Value in tests

The test describes the behaviour of the code; that is, the features that the code provides, and the value that you can expect from those features.

The test doesn’t fully define the behaviour. There’s no definition for what happens if the parameters are negative numbers, for instance, or any indication as to whether the grid can cope with non-integers. There’s no indication of what might cause the behaviour of the grid to change.

Normally, when we have a story, we have some scenarios which are associated with that story. The scenarios form acceptance tests for that story, but they may not completely define the system behaviour. After all, if all the scenarios defined for a story play out, then any bug is just a scenario we didn’t think of – and we still find bugs.

In a story, the story card is just a placeholder for a conversation about that story; the scenarios are there to help you work out if the story has been developed properly.

In a test, the name of the test method forms the ‘story card’ for that piece of code, and the implementation of the test forms the ‘scenarios’. But it’s still just a placeholder for conversation.

Posted in Uncategorized | 2 Comments

Fun things to find in your code

An Http utility class with a getGetMethod method.

Posted in Uncategorized | 2 Comments

Dear XP

A musical tribute to the happiness of pairing, task cards, burn down charts and flowing clouds on summer days. With subtitles.

http://www.youtube.com/watch?v=zpw8h4OGNxg

(Am I going to have this song in my head all day now?)

Posted in Uncategorized | 3 Comments

Automated tests are not a replacement for manual QA

I used to be quite religious over automated testing, but lately I’ve come to realise that sometimes, I might as well run the app and see what happens. Automated tests can’t cover everything. Here’s a few interesting ‘untestables’ that I found while developing my Tetris-like game, Hellbound, with JBehave’s Story framework:

Abstractions that are divorced from the business value

The Glyph (that’s the shape which falls down the pit in the game) falls faster each time it falls. The ‘heartbeat’ which sparks this accelerates gradually. I could always stub the system clock, but I can’t stub out java.lang.Object.wait(). Having a real heartbeat in the automated tests is a pain anyway, because it would take ages for the tests to run.

Dave suggests making a Waiter and functionally verifying it just the once, but it becomes abstracted then from the value I want – which is that the game should become steadily more challenging. The only way to find out whether that behaviour is delivered is to play.

Code that gets collected by the garbage man

After between 5 and 50 glyphs, depending on how fast I was playing, the Glyphs stopped responding to the heartbeat because the garbage man took my listener away. Nice. Since my automated tests are mostly CPU-bound, I think they might take even more glyphs to come across that bug. Maybe it explains the very occasional intermittent failure which I’ve encountered.

Apps that keep going without you

I could only see it with the logging turned on, but the game was still running after I’d closed the frame. I could see the logs of every glyph being created, falling down the (now non-existent) pit, with each fall getting shorter and shorter until eventually the game was over. I had to tie the heartbeat thread to the closing of the window. Maybe this comes under scenarios nobody thought of.

Tests that mysteriously disappear from the build

The only way I’ve found to catch this is to occasionally break an obscure test and check that the build is still broken. Fortunately I only have to remember to do this when I’m in particularly fine coding form and not doing it by accident anyway.

Scenarios nobody thought of

My game works! Left, right, rotate, drop, move down, heartbeat. Of course, you can move the glyph left ten times and straight off the edge of the pit, but we didn’t think of that.

Some thoughts

Manually testing the code you’ve written isn’t just important, it’s also quite fun (especially if you’re writing Tetris). I get a kick out of seeing the value that I’ve been working towards appear; I’m sure you do too.

However, for every bug I’ve mentioned here, there have been 50 that my automated tests have picked up and warned me about; plus they allowed me to eliminate a dozen potential culprits when pinning down the heartbeat bug. Logging did the rest.

Don’t think of automated testing. Think of the value you’re trying to get from your system, and how to find out if you’ve got it. This saves wasting time on untestables, and (for me) creates cleaner, more extensible code, because I’m thinking of the domain while I write it.

Plug

Of course, I don’t think of them as tests, but ‘executable scenarios’. JBehave has come on a long way in the last year and we’re hoping for a 0.9 pre-release soon (when I’ve worked out how to rebuild the website and added some decent examples), followed by a 1.0 release as soon as feedback suggests it’s ready. I’ve used BDD with JUnit on a few projects now with success, but only at a unit level. I’ve shown a couple of customer-proxies (BAs) the stories we’re running in Hellbound and they were quite excited at the idea of helping to write and being able to read the code. So am I. Watch this space.

Posted in Uncategorized | 5 Comments

Deprecate: a definition

Dictionary.com’s “Word of the Day” for the 8th:

deprecate DEP-rih-kayt, transitive verb:
1. [Archaic] To pray against, as an evil; to seek to avert by prayer.

It brings to mind the times I’ve deprecated code with that thought: “Dear God, please, stop anyone from using this.”

I have since learnt that the only way to stop people using deprecated code is to provide an alternative and remove it completely. God helps those who help themselves.

Posted in Uncategorized | 2 Comments

What does your code do? Or pretend to do?

What code does

Code does:

Sequencing: performing actions in a certain order.
Logic: performing actions according to logic.
Transformation: changing data from one form to another.
Utility: getting some data from some other data, eg: "cat,dog,horse".split(",").
State: removing from, adding to or changing state.
Hardware interaction: keyboards, screens, ports, hard disks, etc.
Library interaction: talking to libraries, systems or drivers that encapsulate the above.

If your method or class does more than one of these things, such as performing transformations in a particular sequence, then maybe that’s a good place to start refactoring new methods. Or new classes.

Disclaimers:
The list may not be complete; if you can think of anything else that code does, please let me know!
I’m sure this list isn’t original, but I’m not sure where I got it from. My terminology may not be standard.

Pretending to do it

This list was prompted by Simon’s post on the Rules of Engagement for using mocks (or not). I agree with Simon that:

  1. For every expectation set upon a mock, you must write a corresponding test to verify that the expectation is a realistic one.
  2. Every time you change the behaviour of an object, revisit each and every test that mocks out this behaviour and verify that the expectations used are still valid

Sometimes, though, we really care about the interaction. Not all of the actions above can be defined using stubs. For this reason, and in the spirit of Sun Tzu, who said something like “Win the war before you fight it,” I hereby present my own Rules of Engagement.

  1. Every aspect of behaviour should have a reason for being there. If the code under test is the customer of the mocked or stubbed class, you can define the behaviour of the mocked class.
  2. For every behaviour you add to a class you’re mocking, write an empty test to define that behaviour. For instance, if I mock out a Sheep, I might write:
    public class SheepTest extends TestCase {
        public void testShouldEatAnyAvailableGrass() {
            //TODO
            // or fail("TODO"); if you want to remember to do it before you check in
        }
    }
    

    I can do this before I code my sheep, and implement the real class when I’m done with its customer. This helps deal with Simon’s rule 1.

  3. Make mocked classes behave predictably wherever possible, eg: don’t throw exceptions for things you expect to happen under normal operation, and don’t return null if you don’t have to.
  4. If you change the behaviour of a class which is being mocked out elsewhere, you will (ought to!) break the test. If this happens, consider whether the behaviour as defined is inappropriate. If so, see Simon’s rule 2.
  5. It’s much, much easier to deal with mocks and interactions if the classes under test, and the classes being mocked, aren’t trying to do too much. See the first bit of this post.

I really love mocks. 🙂

Posted in Uncategorized | Leave a comment

Manual testing: are you working back-to-front?

How do you use tests to drive well-designed code, when you’re not able to write automated acceptance tests?

Sometimes we do this, whether there are automated tests or not:

  • Write some code that gets accesses the database (and turns the data into domain objects).
  • Write some code that gets the useful information from the domain objects.
  • Write some code that talks to the front end.
  • Write the front end.
  • Demo the result and get feedback (and hopefully sign off the story).

There’s nothing wrong with this, and it usually works! But here’s another way:

  • Write the front end, but keep the buttons and boxes empty.
  • Demo the result and get feedback.
  • Write the code that talks to the front end. Hard-code or mock some information to check that it works.
  • Demo the result and get feedback.
  • Write the code that uses the domain objects to get the values. Build fake domain objects. Check that it looks exactly the same as it did in the demo.
  • Write the code that accesses the database.
  • Demo the result and get feedback (and hopefully sign off the story).

What are the benefits of doing front-end to back-end, instead of back-to-front?

  • Quick feedback! Always good.
  • QAs can look at the front end, imagine how it will interact with the rest of the system, and write more accurate test plans.
  • You will never write code that you don’t need, because there will always be a customer or some other code that needs it.
  • When you swap pairs, it’s easier to show your new pair how far you’ve got, and what still needs to be done.
  • You don’t have to design every part of the story in your head before you start coding – just do it!
Posted in Uncategorized | 5 Comments

The Cost of Change

This is a quick’n’dirty picture of the cost of change (y) against time (x) on a Big Design Up Front project (red) and an Agile one (green). For the colour-blind, the Agile cost is the one that stabilises with time, rather than growing exponentially.

This is how the argument goes:

  1. In a BDUF project, the requirements are elicited from the customer and written down. If at any point the requirements change, the document must be updated.
  2. Then the requirements are turned into a high level design. If the requirements change, the high level design and the requirements document have to be updated.
  3. Then the high-level design is turned into a more detailed low-level design. If the requirements change, the high level design and the requirements document and the low-level design document have to be updated.
  4. Then the code is done. After that, the code is tested. Then, the code is integrated. Now if the requirements change… well, you get the picture.
  5. In an ideal Agile project, because the code is largely self-documenting, we don’t do any more design up front than we have to and we practice continuous test, *integration, release and many other forms of frequent feedback, the cost of change is kept low.

I would like to remind myself and anyone else who needs it that the cost of change on an Agile project, while comparatively small, is not zero.

Update: The quick’n’dirty explanation and picture above are huge approximations meant to serve as a rough context for the reminder at the bottom – the non-zero cost of change. There are better explanations and more accurate pictures around which have been crafted by far greater authors. Apologies to anyone who thought I was redefining the wheel; I have added the * clauses for clarification.

Posted in Uncategorized | 16 Comments

Ten Tips for the Agile Martian Coach

  1. Communication is important. Ensure that your Martian has a working translator. Provide expletive vocabulary as required.
  2. All Martians look alike. All humans look alike. Wear name badges and teach each other how to pronounce them.
  3. Remember that alcohol may have unexpected side-effects when fed to extra-terrestrial life forms.
  4. At brown bag lunches, prevent your Martian from eating the brown bag. The extra fibre will not be conducive to a good working relationship.
  5. On no account should you tell your Martian that there’s more than one way to skin a cat.
  6. Your Martian may have a higher technical capability than you do. Make careful notes of anything that he produces which seems to break the laws of physics.
  7. Resist the temptation to use time travel to go backwards and give yourself more time to meet important deadlines.
  8. Resist the temptation to use time travel to go forwards and recover the repository from the future, saving yourself the effort of writing all that code.
  9. Some tools are more appropriate for each job than others. There is no job which requires a sub-ether laser set to “annihilate”.
  10. Be careful of misunderstandings when teaching your Martian to pair.
Posted in Uncategorized | 2 Comments