Category Archives: Java

Posts containing Java code

Unit testing tricks: Look ma, no setters!

Here’s a neat trick if you want set an object in a specific state in a unit test, but you don’t want to violate encapsulation:

This seemingly magic code lets me have a protected (but sadly not private) field Account#balance. I can set this field in each individual test method.

It looks very magic, so it deserves a brief explanation:

  1. The first set of curlies create an anonymous subclass of Account. That is: new Account() {}.
  2. The second set of curlies creates an initializer block, that is: a block of code that is added to the constructor.
  3. So in effect: Each test method creates a subclass of Account and modifies the account field in the constructor. This is why Account#balance must be protected instead of private.

This trick (and it is a trick) lets me set up the object under test to any state I want, without needing a special constructor and without breaking encapsulation by adding a setter. However, I’m required to make the fields I want to initialize protected. Additionally, each test method creates one or more new classes. This could potentially affect performance and/or memory use during compilation and/or running of tests. I’ve only used the trick at a small scale, so I don’t know if I’ll run into these issues in the future.

So, what do you think: How big of a “WTF” is this code?

Posted in English, Java | 18 Comments

How to stay ahead

This is a test case from my current project:

It seems pretty run of the mill. A tester will sit down with a bunch of these and try out the application.

Except that the tester in question is not a person! Instead it is a program named Cucumber.

I first learned the ideas behind Cucumber from Dan North at the ROOTS 2005 conference. And this year at the ROOTS 2009 conference Aslak Helles√ły, the creator of Cucumber, will give a tutorial that brings the ideas of Behaviour Driven Development as the next step in effective requirements and testing into the mainstream.

I’ve been attending the ROOTS conferences every year since 2000 and was on the committee for three years. The conference hosts world-class speakers and has a focus on up and coming ideas. It’s a small and intimate conference with tutorial style sessions that lets the speakers go into depth on their areas of expertize.

Do you want to stay years ahead in your field? Go to Bergen for the ROOTS 2009 conference April 27th to 29th.

Posted in Communities, English, Java, Software Development | Leave a comment

Refactoring on @Ignore

Doing the Code Dojo at Oslo XP meetup last Monday, I realized a new concept that I’ve been using unconsciously for a while: I only add to the structure of my system when I have a test that cannot be satisfied by the current design. The rules of test-driven development tells me to wait to create a more advanced design until I have a reason to do so. And that reason should be a failing test. However, the rules of refactoring require all tests to be green during a refactoring. So the failing test must be Ignored during the refactoring.

I revisited these ideas last Wednesday in my second Code Dojo this week in form of the problem of Yahtzee.

If you start solving the scoring rules for the game of yahtzee using the simple examples of “ones”, “twos” and so on, you will run into a problem as you approach, say full house. A full house in yahtzee is scored for example, when you roll three fours and two fives on your five dice. That is:

When I first solved this kata, the test for full house meant I had to take a step back. My solution was to come up with the design of creating a method to calculate the frequency of each die value. This could for example be represented as an array, so that

This refactoring also changes the implementation of ones, twos, etc:

Clearly, I don’t want my tests to fail while I execute this refactoring. This means that the test for “full house” must be @Ignored (or commented out) during this change. Moreover, the existence of the test for “full house” is the very reason I want to introduce this more advanced design.

Thus: Only refactor to more a more complex design while you have an @Ignored test that cannot pass with the current design.

Posted in English, Extreme Programming, Java | 3 Comments

Planning by value

Agile development is easy to understand and hard to do. One of the hardest things to do is to base plans and actions on value instead of effort.

An article by Alistair Cockburn includes a story that illustrates the point:

A boy is behind on his German language home work. He now has to read ten stories and answer a set of question for each. He will be graded on the number of correct answers.

There are several ways our student could attack his problem. The most obvious and most analogous to how many projects are run would be to read all ten stories, read all the questions and then answer them. With this approach he can get into “the zone” of reading stories and perhaps complete his task as quickly as possible. This plan is based around tasks to be executed, and tracks progress by effort expended.

But now comes a few questions: When he’s read all the stories but answered no questions, how much progress has he made? 20%? 70%? How would he know? And if he runs out of time, how will his final grade look?

Working incrementally?
Working incrementally?

A more agile approach would instead be one of incremental delivery: Read one story, answer the questions. When he’s read one story, he know he’s exactly 10% along toward his goal. His speed might increase or decrease over time, so he doesn’t know how much of the effort he’s expended. But he knows how much value he has delivered. And if he completes only four stories, he will at least get scored on the 40% that he completed.

But, inspired by this thinking, the student comes up with an even more aggressive idea: Start with the questions. Read a question and then read enough of the story to answer it. (Or, more realistically: Read all the questions for a story before reading the story. But that’s not as good of an analogy) The approach is analogous to test-driven development. We start with the desired outcome and do exactly what is needed to accomplish it.

An objection to this approach would be that it seems like cheating. But is it? What do you think, gentle reader?

Can this approach be applied to your current project? Even though I didn’t think so at first, it certainly can to mine.

The full article is worth the read. It tries to cover a lot of ground and is a challenging read at times, but it contains many further insights.

Posted in English, Extreme Programming, Java, Software Development | 6 Comments

Five unit testing tips #4: Don’t mock your way into accidental complexity

I’ve all but stopped using mock objects in my tests. The reason is that mocking have had a detrimental effect on the design of my systems. I’ve often ended up having the mocks trick me into adding a needless layer of indirection that does nothing except delegate to the next layer, just to satisfy the mocks.

For a while, I was wondering whether I was the only one with this problem, but then I saw this tutorial on JBehave, which so perfectly illustrates the problem I saw myself doing. Now, I don’t mean to pick on JBehave, or the author of this tutorial. Furthermore, this is not a particularly extreme example of the problem. Rather, the point of this posting is to show that even expert developers run into this trap.

Here is the test from the JBehave tutorial:

In other words, the tab’s notes to be played should be equal to the parsed notes.

Here’s the implementation:

Whoops! We just introduced a layer in the design that does nothing. As a matter of fact, removing the Tab class from the whole example leaves us with a design that’s easier to understand.

Mocks can be great when you really, really need them. And I’m extremely impressed by the power of mockito. But used inappropriately, mocking can trick you into creating accidental complexity and extra layers of code that does nothing.

Posted in English, Java, Software Development | 6 Comments

… but please do repeat me

The hard choice between duplication, paralysis and chaos

A common programmer credo is “Don’t Repeat Yourself” (Pragmatic Programmer) or “Once and only once” (Extreme Programming). Like all credos, we risk following it even when it is not appropriate.

The larger truth is that we have choice between three evils:

  • We can duplicate our code, thus duplicating effort, understanding and being forced to hunt down twice.
  • We can share code and affect everyone who shares the code every time we change to code to better fit our needs. If this is a large number of people, this translates into lots of extra work. If you’re on a large project, you might’ve experienced code storms: Days where you’re unable to get any work done as you’re chasing the consequences of other people’s changes.
  • We can keep shared code unchanging, thus forgoing improvements. Most code I (and I expect, you) write is not initially fit for its purpose, so this means leaving bad code to cause more harm.

I expect there is no perfect answer to this dilemma. When the number of people involved is low, we might accept the noise of people changing code that’s used by others. As the number of people in a project grows, this becomes increasingly painful to everyone involved. At some time, large projects start experiencing paralysis.

If we’re not happy with the state of the code when paralysis sets in, it might be that there’s really only one option left: To eschew the advice of the masters and duplicate the code.

Posted in English, Extreme Programming, Java, Software Development | 5 Comments

Five Unit Tests Tips #3: Parametrized test methods

The following is a trick I don’t use very often, but when I do need it, it comes in very handy. It’s a trick that many developers aren’t aware of, even though it’s been possible to do with JUnit at least since version 3.

Sometimes you want to have a lot of tests that are almost the same, but that contain different arguments. For example, for a yahtzee calculator, you might want to have the following tests:

This is possible with JUnit, but a little trick. You have to construct a test suite manually and add special subclasses of TestCase to it:

The code creates an anonymous inner subclass of TestCase that instead of calling all methods annotated with @Test just executes our specific test. These tests are collected in a normal JUnit TestSuite.

The test is plain JUnit and will run in Maven or your favorite IDE, just as any other tests. The fact that the suite is named after the test class will let Eclipse know where to go when you double click on the test from the test runner.

This trick can be very useful for tests of logic that calculates a results or validates input.

Posted in English, Java, Software Development | 12 Comments

Architecture as tidying up

Unstructured picture
Unstructured picture

I recently started on a new project. Looking over the code base, I saw the familiar structure of many projects: Definitions of classes goes here, persistence logic goes over there, interfaces to the persistence logic goes this other place, code for transforming from one structure to another in yet another place and so on. This is common, neat, and unfortunate.

As an exercise to understand the architecture of this system, I decided to add some new functionality: Displaying some data to the user. I haven’t worked this task oriented with this sort of system before, and so I hadn’t noticed just how extremely clumsy the common structure of these projects is to work with. In order to create the functionality, I had to navigate to around 10 different directories. In each directory, I had to work with one single file, and ignore the tens of files around it with similar names.

Tidied picture
Tidied picture

While watching a few videos from the TED-conference, it finally struck me: We often think that the job of software architecture is to tidy things up, so that things with the same attributes are sorted into neat piles. Too often, the attribute that we chose as the basis for our organization is an incidental, inconsequential one.


Posted in English, Java, Software Development | 7 Comments

Simpler Java deployment?

“The service went down because another service running on the same application server went down.” “You can’t use the improved version of your programming language because you’re running on the same application server as some old applications.” “We can’t help you deploy your application on the application server, because we’re busy with some other application.”

If you’ve ever heard any of these statements, you’ve been victim to the accidental complexity of the application server.


Posted in English, Java | 5 Comments

Keep the build clean

Have you ever looked at a list of compiler warnings the length of an essay on bad coding and thought to yourself: “You know, I really should do something about that… but I don’t have time just now”? On the other hand, have you ever looked at a lone warning that just appeared in a compilation and just fixed it?

When I start a new project from scratch, there are no warnings, no clutter, no problems. But, as the code base grows, if I don’t pay attention, the clutter, cruft, warnings, and problems can start piling up. When there’s a lot of noise, it’s much harder to find the real warning that I really wanted to read among the hundreds of warnings I didn’t care about.

To make warnings useful again, I use a zero-tolerance policy about warnings from the build. Even if the warning isn’t important, I deal with it. If it’s relevant, but not critical, I still fix it. If the compiler warns about a potential null-pointer exception, I fix the cause, even if I “know” the problem will never show up in production. If the embedded documentation (Javadoc or similar) refers to parameters that have been removed or renamed, I clean up the documentation.

If it’s something I really don’t care about and that really doesn’t matter, I ask the team if we can change our warning policy. For example, I find that documenting the parameters and return value of a method in many cases doesn’t add any value, so it shouldn’t be a warning if they are missing. Or, upgrading to a new version of the programming language may make previously okay code now emit warnings. For example, when Java 1.5 introduced generics, all the old code that didn’t specify the generic type parameter would give a warning. This is a sort of warning I don’t want to be nagged about (at least, not yet). Having a set of warnings that are out of step with reality does not serve anyone.

View of Oslo

By making sure that the build is always clean, I will not have to decide that a warning is irrelevant every time I encounter it. Ignoring things is mental work, and I need to get rid of all the unnecessary mental work I can. Having a clean build also makes it easier for someone else to take over my work. If I leave the warnings, someone else will have to wade through what is relevant and what is not. Or more likely, just ignore all the warnings, including the significant ones.

Warnings from your build are useful. You just need to get rid of the noise to start noticing them. Don’t wait for a big clean-up. When something appears that you don’t want to see, deal with it right away. Either fix the source of the warning, suppress this warning or fix the warning policies of your tool. Keeping the build clean is not just about keeping it free of compilation errors or test failures, warnings are an important and critical part of code hygiene.

Posted in English, Java, Software Development | 5 Comments