Cyber Dojo for teaching TDD

I’ve been teaching “Agile Projects” (yes, the title does feel a bit strange) to undergraduate students for a few years, and I’ve always took that opportunity to spend half a day on TDD. That meant me demo’ing a test-first implementation of FizzBuzz, then letting the students take a stab at the Fibonacci series. Yes, all very run-of-the-mill stuff. Understandably, I was always worried that concepts would not be really understood.

This year, I decided to try out Cyber Dojo, a website by Jon Jagger that is essentially a bare-bone IDE, streamlined for TDD. For this, I baited the students by offering bonus exam points for those who submitted the exercise. Also, the exercise was to be done on their own time.

Cyber Dojo is not particularly designed for running exams, and it was lacking around the edges, but it does seem to do the job.

The way it works is by letting the student selects a pre-packaged environment (Java+JUnit, say, or PHP+PHPUnit, or even Erlang+eunit). They would also chose a particular kata from a list of 20 or so, made of well-known exercises. The environment is set up with a simple code file, a test file, and an instruction file. There is also a file containing the output of the test execution and a script for the adventurous who wants to tune how the tests are run. That’s it. No refactoring tools, no syntax highlighting, no reformatting. Just you and the code.

All the student can do, after modifying code, is run the tests. The results are recorded in the output file, and a traffic light icon is displayed in red, yellow or green. It is up to the student to decide when the kata has been completed.

The plan has been to point them to the site, and ask them to email me the identifier for their exercise: the “dojo id” and “animal name”. It is possible for several students to share a dojo, but I figured that encouraging them to start a new dojo each would reduce the risk of cheating by copy/paste.

Upon receiving the dojo details, I would review the sequence of red/green lights (an ideal series would be a repeating sequence of red/green/green, representing writing a test that fails/writing code that passes the test/refactoring), then read the code modified at each step. This would let me see whether the code was truly designed using baby steps — and would let me easily weed out those who copy & pasted the solution from the internet.

Finally, I would then write up my thoughts and email them back to the student. Those who did the exercise early had a chance to do it again, with the benefit of my comments.

One drawback of reviewing TDD exercises, is the time it takes to review the results. It takes me almost 20 mins to read, assign scores, and send comments to the students. With 80 students, that would in theory take more than 24 hours of work. I mitigated this by making the exercise optional and also allowing students to work in pairs. I still got a good 30 to review. What I saw was not very flattering to me as a teacher… but that would be a topic for another post.

Posted in tdd | Comments Off on Cyber Dojo for teaching TDD

Introducing computers to kids in kindergarten

A couple of weeks ago, I organized a workshop based on MaKey MaKey from the 20 children in my daughter’s class in kindergarten. The children were born in 2009, so were around 5 years in age. The plan was to demystify computers by letting them see electronics (the MaKey MaKey kit) and interact with them in fun ways.

This is mostly a step-by-step account of what I did, in the hope it might inspire others.

I started with an overall introduction on computers: “have you seen a computer before?” “can you point me to one?” (I made sure to explain that my smartphone was also a small computer). On the question “what can you do with computers?” I got the expected responses, that is, mostly passive usages such as listening to music (by far the most popular answer), watching movies. Perhaps surprisingly, only one mentioned playing games (this makes sense, since at this age, they are still too clumsy with keyboards; games on tablets work better). A bit disappointingly, a single child mentioned non-passive activities: “looking for cars to rent for the holidays” and “sending letters to people far away” (plus, this was from my own daughter so it didn’t really count).

“Writing letters” was the cue I was hoping for to demonstrate typing letters (they started  learning the alphabet just a few month earlier, so they loved it) and how to move “the little arrow” using the “square” (trackpad).

I then showed the (unplugged) MaKey MaKey board, explaining that it was much the same inside the computer. And then I explained that we were going to type letters using… carrots!

At this point, I took a first group of 4 to another room (I had the option to stay in the classroom or in a corridor next to it, but I was concerned that it would draw the attention of too many children). I had the grand plan to demonstrate how to do stuff with bananas, carrots, gummy bears, plasticine, aluminium sheets, wet pieces of paper… Of course, this hit the reality wall after just the first group.

In the end, here is what works in 10-15 mins.

Typing letters

  1. get the kids to plug the MaKey MaKey into the computer (none tried to force the cable in, to me relief)
  2. get them to plug a wire into a hole next to the letters on the board (a surprising number of kids tried to plug both ends into nearby holes) and poke it with an alligator clip plugged into the earth of the MaKey MaKey board (it turns out that kids of this age do not have enough strength in their fingers to open the jaws of the alligator clip, so I had to plug the cord myself — in a separate event, I witnessed 6-year olds doing fine with this)
  3. watch letters appear on the screen

Carrot piano

  1. remove the wire plugged into the letters
  2. plug 4 alligator clips into the 4 arrows on the board –again, I had to do this myself–; these cords should all be holding semi-rigid wires at their other ends (prepared earlier by myself)
  3. get the kids to plug the wires into the carrots (I had tried with bananas in another occasion, but carrots are a lot more resistant to pounding by little fists); I was expecting them to struggle with that, the carrots being relatively hard, but they all came out brilliantly
  4. open the scratch project “MaKey MaKey Piano“; note that you’ll need internet access for this. What sounds trivial in a different context is made harder at kindergarten where such infrastructure is not available. In my case, I opened the web pages at home in advance (simply making a local copy didn’t work). As a backup, I also set up my phone as a wifi hotspot with 3G connection.
  5. make the kids hold the “earth” wire in one hand, and touch the carrot in the other. Music!

Body drums

  1. for this one, gather all 4 kids around a single computer
  2. get each, except one, to touch a carrot in one hand, and present their other hand with the palm up
  3. open the drums page by artcopycode; that worked better on Chrome than on Firefox, for some reason
  4. get the last kid to hold the earth wire and slap alternatively the palm of each of his friends

This was all done in groups of four children, two per computer. Managing all that by myself was very feasible (the teacher was in the classroom with the rest of the class).

The children had lots of fun! The teacher liked it too, although she was not able to see first hand how it worked. As for me, I liked the fact that I managed to teach a couple of simple concepts, let the children enjoy themselves, and teach them it’s OK to tinker with computers. Also, I got to show off as a cool dad to my daughter and her friends!

For more pointers on to computer-related stuff that can be done with kids of all age, check out my github page (in French): Initiation à la programmation pour les enfants.

Posted in personal | 3 Comments

Avoid branches in test code

Tests should describe a linear story, as opposed to production code. What things we start with, what we do with them, and what we get. Some call this the Given/When/Then pattern, others the Arrange/Act/Assert pattern. This means that the code should be written as a single thread that can be read with as little mental effort as possible. Devant St Vincent de Paul Although it might seem obvious in simple cases, it also means that, for example, you should avoid loops when initializing your test data:

public void can_limit_search_results_to_5()
{
    // I recommend this over a for-loop
    List list = new ArrayList();
    list.add("string");
    list.add("string");
    list.add("string");
    list.add("string");
    list.add("string");
    list.add("string"); // 6

    Store store = new Store(list);

    assertThat(store.findByName("string")).hasSize(5);
}

Similarly, avoid try/catch blocks. In older versions of JUnit, in order to check that an exception was, you had to write code like this:

public void can_fail_when_searching_on_an_invalid_name() {
    try {
        search.findByName("an invalid name");
        fail();
    }
    catch (RuntimeException e) {
        // success
    }
}

Since JUnit 4.0, this can be refactored as: @Test(expected = RuntimeException.class) public void can_limit_search_results_to_ten() { search.findByName(“an invalid name”); } This has the added benefit of producing a more explicit error message from JUnit when the test fails. What if you need to check the content of the exception message? JUnit 4 does offer a mechanism for this, but I find it rather cumbersome. I prefer the catch exception library:

public void can_fail_when_searching_on_an_invalid_name() {
    catchException(search).findByName("an invalid name");

    assertThat(caughtException()).isInstanceOf(RuntimeException.class);
    assertThat(caughtException()).hasMessage("Name is invalid");
}

If you understand French and want to hear more about the Catch Exception library, you might be interesting in this podcast episode I recently published. This is an excerpt of a chapter I’m writing for the upcoming CITCON Chronicles book.

Posted in java | Comments Off on Avoid branches in test code

Test with a test framework idiomatic to your programming language

Code in Java, test in Java. With JavaScript, test in JavaScript. Ideally with a test framework that lets you write your unit tests in a way that does not feel contrived or constrained compared to writing production code.

For example, until version 4.0, JUnit required that test classes extend a special class, TestCase, and that test methods start with a special prefix. These constraints felt rather arbitrary (in truth, they were present mostly for technical reasons) and were replaced with annotations in later versions of JUnit.

In contrast, unit testing your production language in a different language (as advocated here, for example) will require you to adjust your mental state every time you switch from production code to unit test code. Instead, I want as seamless a transition as possible, as I’ll frequently switch from one to the other, especially when practicing test-first style development.

The same advice applies when considering Behavior-Driven Development (BDD) frameworks that come with their own language or formalism such as Cucumber and FitNesse. Although those may have value as acceptance test environments, using them for unit testing will slow down the feedback cycle created by quickly going from reading/writing tests to reading/writing production code. I’d even argue that this aspect of their design is a drawback to doing other forms of testing. Although there are not many of them yet, it is worth putting some effort into finding a high-level test framework that works directly in your favorite programming language (one such example for BDD is Narrative).

Finally, notice how proficient you are in your production code? That comes from years of practice. It also comes from a productive development environment. Use those to your advantage.

This is an excerpt of a chapter I’m writing for the upcoming CITCON Chronicles book.

Posted in test | Comments Off on Test with a test framework idiomatic to your programming language

Name test methods with underscores

In production code, common coding standards for Java recommend writing method names in CamelCase.

retrieveUserDetails()
createABankAccount()

This makes sense when those methods are called from our own code. It feels as if requests are being made to these objects (dear “bankTeller.createABankAccount()”, please). Besides, it follows the conventions in the Java Development Kit and with other projects, making it easy for newcomers to feel at home.

However, methods in unit tests are not called by us. They do not need to represent requests. They also have less pressure to look similar to other public APIs. They do need to tell a story, and a story is best told with space between words. We cannot put spaces in method names, but underscores come close.

should_search_by_name_address()
cannot_fail_when_address_is_not_specified()

This is an excerpt of a chapter I’m writing for the upcoming CITCON Chronicles book.

Posted in java | Comments Off on Name test methods with underscores

Default JDK file encoding and Eclipse, running on Mac OS X

File encoding is notoriously a difficult problem for developers to fully grok. Development environments and IDEs do not always help.

I recently had a test failing under Eclipse, whereas the same test was passing fine in the command line using Maven. Here are some details on the context, and a workaround.

Continue reading

Posted in java | Comments Off on Default JDK file encoding and Eclipse, running on Mac OS X

A classic case of Data Envy

TL;TD: Refactoring classes that have data envy is easy. Do it.

Here is a snippet extracted from the last project I worked on:

// somewhere in a class
asset.setHasAssociatedImage(!StringUtils.isBlankOrNull(imageName));
asset.setImageName(imageName);

// in another class
if (asset.hasAssociatedImage()) {
	image.setUrl(categoryName + "/" + asset.getImageName()));
} else {
	image.setUrl(categoryName + "/" + "error.gif"));
}

If you’re like me, you’ll cringe at the sight. In fact, this is a classic case of Data Envy.
Continue reading

Posted in java | 4 Comments

Avoid annotations with Mockito

On the Mockito mailing list and on Stackoverflow, there are a significant number of questions that actually reveal that the person asking did not perfectly understand what the Mockito annotations do. Indeed, the annotations are rather magical and their behavior is definitely not obvious.

Since they are mostly syntactic sugar (although whether they actually improve readability is debatable), my recommendation is to do without them entirely. Here are a few examples.

Continue reading

Posted in java | 8 Comments

[Musings] Hot Chocolate for the Busy

I used to think that the only way to heat milk properly for preparing hot chocolate was by using a saucepan. I eventually decided to experiment with a microwave oven.

Continue reading

Posted in personal | 1 Comment

Refactoring to Fantom

This post in an introduction to Fantom via the refactoring of Java code.

TL; DR: Fantom is basically a better Java with a very similar syntax, but with lots of little simplifications and some powerful features such as functions. Continue reading

Posted in java | 1 Comment

A novel way to spam blogs for SEO

On March 18th, I received the following email:

On 18 March 2012 16:26, Jen Rhee <thisisjenica@gmail.com> wrote:
Hi Eric,

I came across your site and wanted to share my infographic about Wikipedia and how it’s redefining the way we research. I saw that you had talked about the first wiki developer, Ward Cunningham, which is why I thought you and your readers might find it interesting! Would you be interested in taking a look? Let me know, as I’d love to get your thoughts on it!

Thanks,
Jen R.

I have never heard of that person. I had mentioned Ward Cunningham a couple of times on my blog, although never in relation to wikis. I thought this was a curious email, and decided to ignore it. Continue reading

Posted in misc | Comments Off on A novel way to spam blogs for SEO

Io Language: adding slots to messages

Week 2 of the Seven Languages in Seven Weeks book is about the Io Language. Day 3 is more specifically on how the flow of control (how messages are passed to an object or to its parent) can be hijacked to create a DSL.

In this post, I am going to describe an interesting feature in Io, and how I extended it a bit to enhance an XML generator. Continue reading

Posted in misc | Comments Off on Io Language: adding slots to messages

Create hidden files in Apache VFS with the RAM filesystem type

Apache VFS is a great way to access different file systems in the same way. I particularly like the custom RAM filesystem in my unit tests in order to check code that eventually accesses the actual file system.

For example:

StandardFileSystemManager manager = new StandardFileSystemManager();
manager.init();
manager.resolveFile("ram://root/file.txt").createFile(); // prepare test harness
...
manager.resolveFile("ram://root/file.txt").getName(); // do something useful

Annoyingly, Apache VFS API provides a way to check if a file/folder is hidden, but, although it is always possible to manually create hidden files on your system, there is no way to mark a file as hidden in the RAM filesystem.

manager.resolveFile("ram://root/file.txt").isHidden(); // returns false
manager.resolveFile("ram://root/.file.txt").isHidden(); // also returns false

The solution is to modify the RAM filesystem and customize its checking of the hidden attribute. This means that we need a new RamFileProvider, a new RamFileSystem and finally a new RamFileObject. Continue reading

Posted in java, test | Comments Off on Create hidden files in Apache VFS with the RAM filesystem type

Cleaning up test code

My former colleague David just posted an example of verbose test code on his blog (the parts in French have been translated to English by myself):

/**
 *
 */
@Test
public void testGetCustomerOK() {

  LOGGER.info("======= testGetCustomerOK starting...");

  try {
    CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

    // Check.
    Assert.assertNotNull("Extra not found.", targetDTO);
    Assert.assertEquals("accountIds must be the same.", "ABC99", targetDTO.getAccountId());

  } catch (CustomerBusinessException exception) {
    LOGGER.error("CustomerBusinessException : {}",
	    exception.getCause());
    Assert.fail(exception.getMessage());
  } catch (UnavailableResourceException exception) {
    LOGGER.error("UnavailableResourceException : {}",
	    exception.getMessage());
    Assert.fail(exception.getMessage());
  } catch (UnexpectedException exception) {
    LOGGER.error("UnexpectedException : {}" +
	    exception.getMessage());
    Assert.fail(exception.getMessage());
  } catch (Exception exception) {
    LOGGER.error("CRASH : " + exception.getMessage());
    Assert.fail(exception.getMessage());
  }

  LOGGER.info("======= testGetCustomerOK done.");
}

Let’s see what I’d do with that. Continue reading

Posted in java | 3 Comments

More data on productivity of small teams

“Adding manpower to a late software project makes it later”. The so-called Brooks’s Law on productivity of software project is well known, since Fred Brooks’ seminal work The Mythical Man-Month, first published in 1975.

That is one of the reasons I’m wince a little when a company talks about plans to hire lots of software developers.

This recent study by QSM seems to prove me right. Its conclusion seems to be that Brooks’s Law can be extended to projects that are not late. At any rate, code is not produced at a faster pace with more manpower. Continue reading

Posted in java | 3 Comments