The Compulsive Coder, Episode 4: You Create, It Assigns

roomba long exposure
Image courtesy Chris Bartle. License.

Some languages are destined to be always overly verbose. One feature I’d hoped for in later versions of Java was implicit typing. In C#, for example, you can declare:

var customer = new Customer("Jose Cañusi");

It’s not too hard for the compiler to figure out that customer is of type Customer.

Java still has no implicit typing. Any time you need a non-specific Customer instance, you need the following code:

Customer customer = new Customer("Elmer Sklue");

I’m out of breath doing all that typing! Well, not really: I didn’t do all that typing. But I’ve suppressed a scream too often pairing with folks who do type the word customer three different times.

We have computers to compute for us. Never mind that the Java language is a cranky old uncle, you at least have a Generation Z development environment if you’re using Eclipse or IDEA.

I’m pretty sure I first saw J.B. Rainsberger demonstrating the following tip at least a dozen years ago.

Type the instantiation (right-hand) side of things first:

new Customer("Anne Teak");

Do not type the left-hand side! Instead, press Cmd-1 (Quick Fix; the corresponding keystroke is Alt-Enter in IDEA). Select Assign statement to new local variable and press enter. If you’re young enough to store away another shortcut, use the slightly more effective Cmd-2-L key combination instead.

Unnecessary typing represents distraction, waste, and risk.


Previous Compulsive Coder blog entry: Typing Isn’t the Bottleneck
Next Compulsive Coder blog entry: Extract Method Flow

The Compulsive Coder, Episode 2: Syntax Coloring

eclipseColorWheelNote: I understand that not everyone sees the entire spectrum of color. This blog post is focused on those who are able to clearly distinguish color differences. Perhaps my sentiments and suggestions apply to other visual triggers, which as I understand still exist for many of those diagnosed as color blind.

In 1986, my manager broke down and bought me my very first color monitor–a good deal more expensive than a monochrome monitor. I still remember him saying, “What a waste. What do you need those colors for?” I didn’t have much of an answer other than that it was “easier on the eyes.” Mind you, this is in the days where most software was geared for of 25×80 character-mode, green-on-black terminals. I hooked into an HP/3000 minicomputer, and the OS (MPE-III) wasn’t going to cough up anything particularly interesting with respect to colors.

Today, we take color for granted on our phones and other devices, and know how colors play a significant role in garnering attention and triggering reactions.

And yet. At a customer site where developers code using Eclipse, a first glance tells me that virtually all programmers accept the default color scheme provided; no questions asked. Sigh.

What do Eclipse default colors look like? Take a look:

eclipseBlah

Pretty uninteresting, eh? Black, purple, blue. Neither panache nor nuance. Nothing really stands out.

In fact, Eclipse emphasizes the wrong things. Keywords such as public and void and throw are bold and purple, intended to stand out. Yet keywords are often the least interesting thing about a chunk of code; they are likely the thing I need to digest last. Even worthless comments stand out with the Eclipse default color scheme! At least statics are italicized; that seems OK. It’s also good that fields are colored–but unfortunately they are dark blue, which contrasts little with the other elements.

What should stand out in Java code? Fields, certainly. Where a class’s code interacts with fields is a key piece of information. As such, I configure my fields to be bright orange. For most people, the orange fields stand out like sore thumbs. Here’s the same code with my current orange-featuring color scheme:

eclipseColor

Where parameters and local variables are used is also relevant. Being able to track on a specific color for each (gold and green, respectively) can make it easier to track state changes across the body of a method (although the Eclipse feature Mark Occurrences is more useful for tracking a specific variable).

The return keyword isn’t typically very interesting, unless it occurs somewhere other than at the end of a method. No one uses underlining any more, but I’ve found that doing so can help me more quickly spot an early return.

The use of inherited fields–an odd practice, questionable at best (and one that this code doesn’t feature)–really stands out and annoys me, because I’ve made them bright red.

Emphasizing important elements is valuable, but so is de-emphasizing less relevant elements. Comments, too often not to be trusted, are now a light gray, barely visible. On days where I’m particularly affronted with the worthlessness of comments, I make them white.

While my color choices (which I change from time to time) suit me just fine, they might not suit you, however. You and I will disagree on precisely what the “right” things are to emphasize or de-emphasize. That’s ok. The key thing is to make a conscious, informed choice, and to pay attention over time to what the colors tell you about your code.

The world is full of color. Bring your IDE into that world.


Previous Compulsive Coder blog entry: The Stub Comment
Next Compulsive Coder blog entry: Typing Isn’t the Bottleneck

You can find my current color preferences for Eclipse here. You can merge these entries into the file ./.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs in your workspace.

The Compulsive Coder, Episode 1: The Stub Comment

Some things keep coming back, such as facial hair, indigestion, and platform shoes. And for me, Java. I’m once again back in the Java world for a current engagement, and accordingly I’m again working with Eclipse.

The instant I began pairing with folks on Eclipse, my “Felix sense” kicked in, and I became unbearably indignant about the horrible defaults that too many developers simply accept. No one could tolerate more than one Ungar-ism at a time, so in this post I’ll focus on a real simple one:

public Holding findBy(String key) {
   // TODO Auto-generated method stub
   return null;
}
422769556_4094cecb03_m
Image courtesy Adam Engelhart; license

My immediate reaction was probably much like this.

A stub comment! Egads! Why in the world would people pollute their code with stub comments? Coders use their powerful IDE to auto-generate a new, empty method, but then have to waste time picking up and deleting these ugly, useless little stub comments. And horror of horrors, sometimes they don’t–I just saw a screencast where the programmer didn’t even flinch as he created and abandoned a stub comment!

The reason? Maybe it’s the 45-second effort Eclipse requires to turn off these wonderfully useless “auto-generated method stubs.” Or the painfully inadequate system for saving and restoring preferences like this (they’re all over the place), a consideration that crops up whenever you create a new workspace.

Well, I don’t want you to be able to say “I didn’t learn anything from Jeff’s blog.” Let’s start incrementing some Compulsive Coder Principles and Techniques.

Compulsive Code Principle #1
A laziness mentality is acceptable as long as you really do minimize as much work as possible. Creating stubs that need to be deleted isn’t maximally lazy.
Compulsive Coder Technique #1
Open the Eclipse Preferences dialog. Select Java->Code Style->Code Templates. (You can find it quickly by typing code templates and pressing Enter). In the right-hand side of the dialog, select Code->Method body. Click the Edit… button. Change the template’s pattern from:

// ${todo} Auto-generated method stub
${body_statement}

to:

${body_statement}

Click the OK button.

An alternative choice: Change the template to:

throw new UnsupportedOperationException("not yet implemented");

It’s an uglier version of a stub! … but, it’s so ugly it forces you to get rid of it. Where it can be helpful is in keeping you to the red-green-refactor cycle of TDD–the thrown exception will most certainly result in a failing test.

Whichever route you choose, similarly change the Code Template for Constructor body and Catch block body.

I bet you won’t ever miss the auto-generated method stubs!

Stay tuned for more Ungarisms.


Next Compulsive Coder blog entry: Syntax Coloring

Running Google Maps in an AVD

After a couple failed attempts, I managed to successfully run com.example.mapdemo in an Android Virtual Device (AVD). It’s not tough, but required cobbling together instructions from a variety of sources.

The following instructions work for the ADT installed under Ubuntu, version linux-x86-20130522. I make no guarantee that these steps will work for you. It’s possible that some of the steps are extraneous.

  1. Using the Android SDK Manager, install Google Play Services (v7).

  2. Using the Android SDK Manager, install Google APIs (v3) (located under Android 4.2.2 (API 17)).

  3. Using the Android Virtual Device Manager, create an AVD with a target of Android 4.2.2 – API Level 17. (I created mine with a 4.65″ 720p, not sure if that’s important.)

  4. Start the AVD

  5. Download two application package files (APKs):

    com.google.android.gms-(3.1.36).apk
    com.android.vending-4.1.6.apk

  6. Install the APKs using adb (located in the ADT directory ./sdk/platform-tools):

    adb install com.android.vending-4.1.6.apk
    adb install com.google.android.gms-(3.1.36).apk

  7. Restart the AVD

  8. Copy ./sdk/extras/google/google_play_services/libproject/google-play-services_lib/ to your Android projects area.

  9. Create a project for Google Play Services (projects needing to use Google Maps will need to depend on this):
    Import->Android->Existing Android Code Into Workspace.
    Navigate to ./sdk/extras/google/google_play_services/libproject and select google-play-services-lib.

  10. Create a project for the map samples:
    Import->Android-Existing Android Code Into Workspace.
    Navigate to ./sdk/extras/google/google_play_services/samples and select the maps directory.

  11. Create a Google Maps API key (note: these steps supposedly will not work for your production deployment):

    • Copy the SHA1 from your Android Debug keystore. Here’s the instructions I used under Ubuntu to display the contents of the keystore:

      keytool -list -v -keystore ~/.android/debug.keystore

      By default, the password for the keystore is android.

    • Go to https://code.google.com/apis/console and select API Access from the menu (to the left).

    • Click the button marked Create new Android Key….

    • Paste in your SHA1, append a semicolon, then append com.example.mapdemo

    • Click the Create button.

    • Copy the API key into the paste buffer (you will use it in the next step).

  12. Configure the map sample project:

    • From the project’s build path settings, Add External JAR: ./sdk/extras/android/support/v4/android-support-v4.jar

    • Go to the Order and Export tab, and export android-support-v4.jar

    • Go to Properties->Android. In the Library section, add the google_play_services_lib project as a dependency. (You will need to open google-play-services_lib if it is not already.)

  13. Edit AndroidManifest.xml to contain your API key: In MainActivityManifest.xml, ensure you have a meta-data element with something like the following:

     <meta-data android:name="com.google.android.maps.v2.API_KEY"
               android:value="AIzaSyCawgR4hVSiAzHIg4wJMbg7jvNyt-KZNgs"/>
    

    Substitute your API key for the android:value attribute. The meta-data element is a direct child of <application>.

  14. Edit AndroidManifest.xml to contain appropriate permissions. For example (don’t forget to substitute your package name):

    <permission
            android:name="com.langrsoft.plangrok.permission.MAPS_RECEIVE"
            android:protectionLevel="signature" />
    
        <uses-permission android:name="com.langrsoft.plangrok.permission.MAPS_RECEIVE" />
    
  15. Run it!

    Here are some of the links I used to piece this together:

    Google APIs Console
    Install Google Play Services SDK
    Sample code
    Getting the Google Maps Android API
    Getting the Google Maps API Key
    Emil’s Design (a useful blog entry)

    Please let me know if I missed any steps or if you discovered something else.

A Smackdown Tool for Overeager TDDers

smackdown!
Image source: https://commons.wikimedia.org/wiki/File:Cross_rhodes_on_gabriel.jpg

I’ve always prefaced my first test-driven development (TDD) exercises by saying something like, “Make sure you write no more code than necessary to pass your test. Don’t put in data structures you don’t need, for example.” This pleading typically comes on the tail of a short demo where I’ve mentioned the word incremental numerous times.

But most people don’t listen well, and do instead what they’ve been habituated to do.

With students in shu mode, it’s ok for instructors to be emphatic and dogmatic, smacking students upside the head when they break the rules for an exercise. It’s impossible to properly learn TDD if you don’t follow the sufficiency rule, whether deliberately or not. Trouble is, it’s tough for me to smack the heads of a half-dozen pairs all at once, and some people tend to call in HR when you hit them.

The whole issue of incrementalism is such an important concept that I’ve introduced a new starting exercise to provide me with one more opportunity to push the idea. The natural tendency of students to jump to an end solution is one of the harder habits to break (and a frequent cause of students’ negative first reaction when they actually try TDD).

I present a meaty first example (latest: the Soundex algorithm) where all the tests are marked as ignored or disabled, a great idea I learned from James Grenning. In Java, the students are to un-@Ignore tests one-by-one, simply getting them to pass, until they’ve gotten all tests to pass. The few required instructions are in the test file, meaning they can be hitting this exercise about two minutes after class begins.

Problem is, students have a hard time not breaking rules, and always tend to implement too much. As I walk around, I catch them, but it’s often a little too late. Telling them that they need to scrap their code and back up isn’t what they want to hear.

So, I built a custom test-runner that will instead fail their tests if they code too much, acting as a virtual head-smacking Jeff. (I built a similar tool for C++ that I’ve used successfully in a couple C++ classes.)

Here’s the (hastily built) code:

import org.junit.*;
import org.junit.internal.*;
import org.junit.internal.runners.model.*;
import org.junit.runner.*;
import org.junit.runner.notification.*;
import org.junit.runners.*;
import org.junit.runners.model.*;

public class IncrementalRunner extends BlockJUnit4ClassRunner {

   public IncrementalRunner(Class klass) 
         throws InitializationError {
      super(klass);
   }

   @Override
   protected void runChild(
         FrameworkMethod method, RunNotifier notifier) {
      EachTestNotifier eachNotifier = 
         derivedMakeNotifier(method, notifier);
      if (method.getAnnotation(Ignore.class) != null) {
         runIgnoredTest(method, eachNotifier);
         return;
      }

      eachNotifier.fireTestStarted();
      try {
         methodBlock(method).evaluate();
      } catch (AssumptionViolatedException e) {
         eachNotifier.addFailedAssumption(e);
      } catch (Throwable e) {
         eachNotifier.addFailure(e);
      } finally {
         eachNotifier.fireTestFinished();
      }
   }

   private void runIgnoredTest(
         FrameworkMethod method, EachTestNotifier eachNotifier) {
      eachNotifier.fireTestStarted();
      runExpectingFailure(method, eachNotifier);
      eachNotifier.fireTestFinished();
   }

   private EachTestNotifier derivedMakeNotifier(
         FrameworkMethod method, RunNotifier notifier) {
      Description description = describeChild(method);
      return new EachTestNotifier(notifier, description);
   }

   private void runExpectingFailure(
         final FrameworkMethod method, EachTestNotifier notifier) {
      if (runsSuccessfully(method)) 
         notifier.addFailure(
            new RuntimeException("You've built too much, causing " + 
                                 "this ignored test to pass."));
   }

   private boolean runsSuccessfully(final FrameworkMethod method) {
      try {
         methodBlock(method).evaluate();
         return true;
      } catch (Throwable e) {
         return false;
      }
   }
}

(Note: this code is written for JUnit 4.5 due to client version constraints.)

All the custom runner does is run tests that were previously @Ignored, and expect them to fail. (I think I was forced into completely overriding runChild to add my behavior in runIgnoredTest, but I could be wrong. Please let me know if you’re aware of a simpler way.) To use the runner, you simply annotate your test class with @RunWith(IncrementalRunner.class).

To effectively use the tool, you must provide students with a complete set of tests that supply a definitive means of incrementally building a solution. For any given test, there must be a possible implementation that doesn’t cause any later test to pass. It took me a couple tries to create a good sequence for the Soundex solution.

The tool is neither foolish-proof nor clever-proof; a small bit of monkeying about and a willingness to deliberately cheat will get around it quite easily. (There are probably a half-dozen ways to defeat the mechanism: For example, students could un-ignore tests prematurely, or they could simply turn off the custom test-runner.) But as long as they are not devious, the test failure from building too much gets in their face and smacks them when I’m not be around.

If you choose to try this technique, please drop me a line and let me know how it went!

Easier Testing Using the SRP

This simple file monitor class notifies listeners when a watched file is modified:

public class FileMonitor {
 private Set<FileChangeListener> listeners =
    new HashSet<FileChangeListener>();
 private int duration;
 private File file;
 private long lastModified;

 public FileMonitor(String filename, int duration) {
     this.file = new File(filename);
     lastModified = file.lastModified();
     this.duration = duration;
 }

 public void start() {
     boolean isDaemon = true;
     long initialDelay = duration;
     new Timer(isDaemon).schedule(
        new FileMonitorTask(), initialDelay, duration);
 }

 public void addListener(FileChangeListener listener) {
     listeners.add(listener);
 }

 class FileMonitorTask extends TimerTask {
     @Override
     public void run() {
         if (file.lastModified() > lastModified) {
             lastModified = file.lastModified();
             for (FileChangeListener listener: listeners) {
                 listener.modified();
             }
         }
     }
  }
}

A FileMonitor schedules a TimerTask that just checks the modified date from time to time, and compares it to the last modified date. The code above seems like a typical and reasonable implementation. FileMonitorTask could be an anonymous inner class, of course. I spent more time than I would have preferred test-driving this solution, since I made the mistake of test-driving it as a single unit. These tests had to deal with the vagaries of threading due to the Timer scheduling.

import java.io.*;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;

public class FileMonitorTest {
 private static final String FILENAME = "FileMonitorTest.properties";
 private static final int MONITOR_DURATION = 1;
 private static final int TIMEOUT = 50;
 private FileMonitor monitor;
 private File file;
 private List<FileChangeListener> fileChangeNotifications;
 private Thread waitThread;

 @Before
 public void initializeListenerCounter() {
     fileChangeNotifications = new ArrayList<FileChangeListener>();
 }

 @Before
 public void createFileAndMonitor() throws IOException {
     FileUtils.writeFile(FILENAME, "property=originalValue");
     file = new File(FILENAME);
     monitor = new FileMonitor(FILENAME, MONITOR_DURATION);
 }

 @After
 public void deleteFile() {
     FileUtils.deleteIfExists(FILENAME);
 }

 @Test
 public void shouldNotifyWhenFileModified() throws Exception {
     monitor.addListener(createCountingFileChangeListener());
     waitForFileChangeNotifications(1);

     monitor.start();

     alterFileToChangeLastModified();
     joinWaitThread();
     assertEquals(1, numberOfFileChangeNotifications());
 }

 @Test
 public void shouldSupportMultipleListeners() throws Exception {
     monitor.addListener(createCountingFileChangeListener());
     monitor.addListener(createCountingFileChangeListener());
     waitForFileChangeNotifications(2);

     monitor.start();

     alterFileToChangeLastModified();
     joinWaitThread();
     assertEquals(2, numberOfFileChangeNotifications());
     assertAllListenersDistinctlyNotified();
 }

 @Test
 public void shouldOnlyReportOnceForSingleModification()
         throws InterruptedException {
     // slow--must wait on timeout. Better way?
     monitor.addListener(createCountingFileChangeListener());
     waitForFileChangeNotifications(2);

     monitor.start();

     alterFileToChangeLastModified();

     joinWaitThread();
     assertEquals(1, numberOfFileChangeNotifications());
 }

 @Test
 public void shouldReportMultipleTimesForMultipleModification()
     throws InterruptedException {
     monitor.addListener(createCountingFileChangeListener());
     waitForFileChangeNotifications(1);

     monitor.start();

     alterFileToChangeLastModified();
     joinWaitThread();

     waitForFileChangeNotifications(2);
     alterFileToChangeLastModified();
     joinWaitThread();

     assertEquals(2, numberOfFileChangeNotifications());
 }

 private FileChangeListener createCountingFileChangeListener() {
     return new FileChangeListener() {
         @Override
         public void modified() {
             fileChangeNotifications.add(this);
         }
     };
 }

 private int numberOfFileChangeNotifications() {
     return fileChangeNotifications.size();
 }

 private void waitForFileChangeNotifications(final int expected) {
     waitThread = new Thread(new Runnable() {
         @Override
         public void run() {
             while (numberOfFileChangeNotifications() != expected)             {
                 sleep(1);
             }
         }
     });
     waitThread.start();
 }

 private void sleep(int ms) {
     try {
         Thread.sleep(ms);
     } catch (InterruptedException exception) {
         fail(exception.getMessage());
     }
 }

 private void alterFileToChangeLastModified() {
     file.setLastModified(file.lastModified() + 1000);
 }

 private void joinWaitThread() throws InterruptedException {
     waitThread.join(TIMEOUT);
 }

 private void assertAllListenersDistinctlyNotified() {
     Set<FileChangeListener> notifications =
         new HashSet<FileChangeListener>();
     notifications.addAll(fileChangeNotifications);
     assertEquals(fileChangeNotifications.size(), 
                  notifications.size());
 }
}

Wow, that’s a bit longer than I would have hoped. Yes, there are better ways to test the threading. And there may be better threading mechanisms to implement the monitor, although I think the Timer is pretty simple. I don’t do enough threading, so I usually code a “familiar” solution (i.e. something I already know well) initially, and then refactor into a more expressive and concise solution. I’m pretty sure this test is flawed. But rather than invest in fixing it, I reconsidered my design (by virtue of wanting an easier way to test it).

The SUT is really two classes, the monitor and the task. Each one can easily be tested separately, in isolation, as a unit. Sure, I want to see the threading in action, but perhaps that’s better relegated to an integration test (which might also double as an acceptance test). I decided to change the solution to accommodate more focused and more robust tests. The file monitor tests are pretty much what was there before (with some small additional refactorings), except that there’s now no concern over threading–I just test the run method:

import java.io.*;
import org.junit.*;
import static org.mockito.Mockito.*;
import org.mockito.*;

public class FileMonitor_TaskTest {
 private static final String FILENAME = "FileMonitorTest.properties";
 private FileMonitor.Task task = new FileMonitor.Task(FILENAME);
 @Mock
 private FileChangeListener listener;

 @Before
 public void initializeMockito() {
     MockitoAnnotations.initMocks(this);
 }

 @BeforeClass
 public static void createFile() throws IOException {
     FileUtils.writeFile(FILENAME, "property=originalValue");
 }

 @AfterClass
 public static void deleteFile() {
     FileUtils.deleteIfExists(FILENAME);
 }

 @Before
 public void createTask() {
     task = new FileMonitor.Task(FILENAME);
 }

 @Test
 public void shouldNotNotifyWhenFileNotModified() {
     task.addListener(listener);
     task.run();
     verify(listener, never()).modified();
 }

 @Test
 public void shouldNotifyWhenFileModified() throws Exception {
     task.addListener(listener);
     changeFileLastModifiedTime();

     task.run();

     verify(listener, times(1)).modified();
 }

 @Test
 public void shouldSupportMultipleListeners() throws Exception {
     task.addListener(listener);
     FileChangeListener secondListener = mock(FileChangeListener.class);
     task.addListener(secondListener);

     changeFileLastModifiedTime();
     task.run();

     verify(listener, times(1)).modified();
     verify(secondListener, times(1)).modified();
 }

 @Test
 public void shouldOnlyReportOnceForSingleModification() 
         throws InterruptedException {
     task.addListener(listener);

     task.run();
     changeFileLastModifiedTime();
     task.run();
     task.run();

     verify(listener, times(1)).modified();
 }

 @Test
 public void shouldReportMultipleTimesForMultipleModification() 
          throws InterruptedException {
     task.addListener(listener);

     task.run();
     changeFileLastModifiedTime();
     task.run();
     changeFileLastModifiedTime();
     task.run();

     verify(listener, times(2)).modified();
 }

 private void changeFileLastModifiedTime() {
     File file = new File(FILENAME);
     file.setLastModified(file.lastModified() + 1000);
 }
}

I introduced Mockito to provide a simple verifying stub for the listener. I suppose I should also stub out interactions with File, but I’ll incur the speed penalty for now. Next, I needed to test the remaining FileMonitor code. To do this involved proving that it creates and schedules a task appropriately using a timer, and that it handles listeners appropriately.

import xxx.CollectionUtil;
import java.util.Timer;
import org.junit.*;
import org.mockito.*;
import static org.mockito.Mockito.*;

public class FileMonitorTest {
 @Mock
 private Timer timer;

 @Before
 public void initializeMockito() {
     MockitoAnnotations.initMocks(this);
 }

 @Test
 public void shouldScheduleTimerWhenStarted() {
     String filename = "filename";
     long duration = 10;
     FileMonitor monitor = new FileMonitor(filename, duration) {
         @Override
         protected Timer createTimer() {
             return timer;
         }
     };
     monitor.start();
     verify(timer).schedule(any(FileMonitor.Task.class), 
         eq(duration), eq(duration));
 }

 @Test
 public void shouldDelegateListenersToTask() {
     FileChangeListener listener = mock(FileChangeListener.class);
     FileMonitor monitor = new FileMonitor("", 0);
     monitor.addListener(listener);

     CollectionUtil.assertContains(
         monitor.getTask().getListeners(), listener);
  }
}

The design of the production code had to change based on my interest in better tests. A number of small, incremental refactoring steps led me to this solution:

import java.io.*;
import java.util.*;

public class FileMonitor {
 private final long duration;
 private Task task;

 public FileMonitor(String filename, long durationInMs) {
     task = new Task(filename);
     this.duration = durationInMs;
 }

 public void start() {
     long initialDelay = duration;
     createTimer().schedule(task, initialDelay, duration);
 }

 protected Timer createTimer() {
     final boolean isDaemon = true;
     return new Timer(isDaemon);
 }

 Task getTask() {
     return task;
 }

 public void addListener(FileChangeListener listener) {
     task.addListener(listener);
 }

 static class Task extends TimerTask {
     private final File file;
     private long lastModified;
     private Set<FileChangeListener> listeners = 
         new HashSet<FileChangeListener>();

     Task(String filename) {
         this.file = new File(filename);
         lastModified = file.lastModified();
     }

     public void addListener(FileChangeListener listener) {
         listeners.add(listener);
     }

     Set&lt;FileChangeListener&gt; getListeners() {
         return listeners;
     }

     @Override
     public void run() {
         if (file.lastModified() > lastModified) {
             lastModified = file.lastModified();
             for (FileChangeListener listener: listeners) {
                 listener.modified();
             }
         }
     }
 }
}

Well, most interestingly, I no longer have any tests that must deal with additional threads. I test that the monitor delegates appropriately, and I test that the task works properly when run. I still want the integration tests, but I think they can be relegated to a higher, acceptance level test for the story:

reload properties at runtime

Otherwise, at this point, I have a high level of confidence in my code. I know the Timer class works, and I know my two classes work, and I’ve also demonstrated to myself that they all work together. I’m ready to move on. Some additional relevant points:

  • Threading is tough to get right, and it can be even tougher to test it.
  • My final solution is a few more lines of code due to supporting my interest in more focused testing. I’m ok with the additional code because of the flexibility having the tests gives me, and more often than not, having them allows me to easily eliminate duplication elsewhere.
  • It’s hard to be overdo the SRP. Far more classes than not weigh in the wrong direction of too many responsibilities.
  • The original solution, probably fine otherwise, is what you might expect from someone uninterested in TDD. It works (I think) but it represents rigid code, code that is more costly to change.

 

Cute Little Abstractions

I’m refactoring several classes of over 2000 lines each. These are classic god-classes that mediate a handful of stubby little data-centric classes around them. I reduced the first, primary domain class by over 1100 lines, to under 1500, by simply pushing responsibilities around. Adding tests after the fact (using WELC techniques, of course) gave me the confidence to refactor. In just a few hours, I’ve been able to completely eliminate about 700 lines so far out of the 1100 that were shifted elsewhere. I’m loving it!

After cleaning up some really ugly code, I ended up with better (not great) code:

private boolean containsThreeOptionsSameType() {
   Map<String, Integer> types = new HashMap<String, Integer>();
   for (Option option : options)
      increment(types, option.getType());
   return count(types, Option.ALPHA) >= 3 || 
          count(types, Option.BETA) >= 3 || 
          count(types, Option.GAMMA) >= 3 || 
          count(types, Option.DELTA) >= 3;
}

private int count(Map<String, Integer> map, String key) {
   if (!map.containsKey(key))
      return 0;
   return map.get(key);
}

private void increment(Map<String, Integer> map, String key) {
   if (!map.containsKey(key))
      map.put(key, 1);
   else
      map.put(key, map.get(key) + 1);
}

I could clean up the complex conditional on the return statement (perhaps calling a method to loop through all types). Also, the count and increment methods contain a bit of duplication.

More importantly, the count and increment methods represent a missed abstraction. This is very common: We tend to leave little, impertinent, SRP-snubbing, OCP-violating methods lying about, cluttering up our classes.

(Aside: I’m often challenged during reviews about exposing things so I can test them. Long-term, entrenched developers are usually very good about blindly following the simple rule about making things as private as possible. But they’re perfectly willing to throw OO concept #1, cohesion, completely out the window.)

I decided to test-drive the soon-to-be-no-longer-missing abstraction, CountingSet. I ended up with an improved implementation of increment by eliminating the redundancy I spotted above:

import java.util.*;

public class CountingSet<T> {
   private Map<T, Integer> map = new HashMap<T, Integer>();

   public int count(T key) {
      if (!map.containsKey(key))
         return 0;
      return map.get(key);
   }

   public void add(T key) {
      map.put(key, count(key) + 1);
   }
}

Some developers would be appalled: “You built a cruddy little class with just four lines of real code? And for only one client?” And further: “It’s only a subset of a counting set, where are all the other methods?”

Sure thing, buddy. Here’s my client:

private boolean containsThreeOptionsSameType() {
   CountingSet<String> types = new CountingSet<String>();
   for (Option option : options)
      types.add(option.getType());
   return types.count(Option.ALPHA) >= 3 || 
          types.count(Option.BETA) >= 3 || 
          types.count(Option.GAMMA) >= 3 || 
          types.count(Option.DELTA) >= 3;
}

My client now only contains intent. The small ugliness with the parameterized map and boxing is now “information hidden.” I also have a simple reusable construct–I know I’ve had a similar need several times before. As for building and/or using a fully-functional CountingSet, there’s something to be said for creating “adapter” classes with the smallest possible, and most meaningful, interface.

Good enough for now. Don’t hesitate to create your own cute little abstractions!

Eclipse Auto Insert

In Eclipse, I use Ctrl-1 and Ctrl-Space so much that the wear on those three keys is noticeably more than the others.

By default, adding a new (JUnit 4 style) test is a matter of typing “test,” then hitting ctrl-space to bring up the appropriate code template. Problem is, Eclipse brings up a number of choices, and hitting enter requires ensuring the right thing is selected (it’s not always in first position) and then pressing enter. I’ve lived with this so far and didn’t think much about it until last night, when I created over 50 tests in a 90-minute session, and really resented the overhead.

I edited the template and figured checking the “Auto Insert” box would solve the problem. No dice–Eclipse presents other choices when I type “test,” such as one that just inserts the lone @Test annotation. What if I rename the “test” code template to a unique name, like “tst?” No, I get a list with two things–my template, and an option to create a method stub whose name is “tst.” No auto insert! I tried a couple other things, such as introducing a special character so that Eclipse would think it couldn’t possibly create a method with that name. That didn’t work (I don’t recall specifically what happened).

I know auto insert works in Eclipse, because I can go into the body of a method, type “sysout” and then press Ctrl-space, and Eclipse auto-completes to “System.out.println()” immediately. It requires no selection on my part. This tells me that auto insert works only if there’s one and only one possible selection. Unfortunately, it looks like that will never be the case outside a method but within the class (i.e. where one can create a “Java type member”)–any template name could also represent the name for a new method stub.

Keystrokes, then, what about assigning keystrokes? Aha. In the General->Keys preference page, I filtered for “content assist.” The choice named simply Content Assist is the one triggered by Ctrl-Space, but another choice is Content Assist (type: Template Proposals), by default assigned no keyboard shortcut. I assigned Ctrl-\ to content assist for template proposals. Now I just type “test” Ctrl-\ and I have my test method stub.

I didn’t really want another key combination, mostly because I prefer to go by IDE defaults. My pairing sessions run me through a wide variety of development environments (at last count, within the past year or so, 10 different C++ editors and 3 different Java IDEs), so it’s easiest to not create dependencies on my own personal reworking of the key mappings.

Ah well, I suppose there are a few key mappings I’ll just have to remember to configure. This is the second one I will want universally for Eclipse; the other is Rerun JUnit Test.

My wish for Eclipse is improved pairing support. The simple idea: you make your key mappings available via a URI. The first time you pair with someone, you add this to Eclipse. From there, a universally defined keystroke allows you toggle through or select from the keymaps.
Comments:

Type the template you would like to use and hit ctrl+space twice. Eclipse will bring the list with choices filtered down to templates.

Auto insert works if the template you typed is the only choice possible. That may work if you delete the old style “test” template. However it still requires you to press ctrl+space twice.

Thanks Igor. I wasn’t aware of the ctrl-space double-press. You still have to hit enter! So, it’s ctrl-space-space-enter. I would have thought this wouldn’t be required since it’s configured as auto-insert. The double-key-press would be ok, but requiring a third sucks. I like my solution better except that it’s not default behavior.

That’s why I used to live with it 😀

I don’t so much love it, but I’ve changed the the templates so that the one I want (JUnit 4 in my case) is “tst“.

Works. 🙂
MB

Right, that was my first thought, and I’m just bugged by the need to look at an unnecessary popup.

You’re right, bugs me too. Would love the “syso” behavior. I’ve been messing around with Eclipse plugins recently, maybe I’ll dig around a bit.

Cheers, MB

Violating Standards in Tests

Should your test code be subject to the same standards as your production code? I believe there should be different sets of standards. I am collecting interesting idioms that are normally shunned in good production code, but are acceptable and advantageous in test code.

An obvious example is the use of macros in tools like James Grenning’s CppUTest. The testing framework (an updated version of CppUnitLite) requires programmers to use macros to identify test functions:

TEST(HelloWorld, PrintOk)
{
   printHelloWorld();
   STRCMP_EQUAL("Hello World!n", buffer); 
}

No self-respecting C++ programmer uses macros anymore to replace functions; per Scott Meyers and many others, it’s fraught with all sorts of problems. But in CppUTest, the use of macros greatly simplifies the work of a developer by eliminating their need to manually register the name of a new test with a suite.

Another example is the use of import static in Java. The general rule of thumb, suggested by Sun themselves, is to not overuse import static. Deleting the type information for statically scoped methods and fields can obscure understanding of code. It’s considered appropriate only when use of static elements is pervasive. For example, most developers faced with coding any real math do an import static on the java.lang.Math functions.

However, I use static import frequently from my tests:

import static org.junit.Assert.*;
import org.junit.*;
import static util.StringUtil.*;

public class StringUtilCommaDelimitTest {
   @Test public void degenerate() {
      assertEquals("", commaDelimit(new String[] {}));
   }

   @Test public void oneEntry() {
      assertEquals("a", commaDelimit(new String[] {"a"}));
   }
   ...
}

Developers unquestioningly use import static for JUnit 4 assertions, as they are pervasive. But the additional use here is for the method commaDelimit, which is defined as static in the target class StringUtil. More frequently, I’ll have the test refer to (statically defined) constants on the target class. For a test reader, it becomes obvious where that referenced constant would be defined.

What other coding standards are appropriate for tests only, and not for production code?

Revisiting BDD in Java

My initial reaction a few years ago to BDD implementations in Java was less than stellar. Since then, I revisited them a couple times, and now I’m digging into them again. They’re still around, so someone must be getting value out of them. I certainly have gotten some mileage around naming and organizing my tests in a more BDD fashion.

Right now, I’m being lazy, and haven’t done diligent research. But my initial internet searches suggest that there are a handful of tools, none of them the de facto standard. I remember my doctor once saying, “We have about a hundred ways to treat this [a plantar wart]. Usually when there are so many ways, it means we don’t know what we’re doing.”

I started looking at one framework in more depth, and coded some straightforward examples. Didn’t seem so bad, until I looked to code a more involved assertion. Here’s one (contrived but simple) example:

Ensure.that(name, and(contains("Langr"), startsWith("J")));

One of the core principles of BDD is “getting the words right.” I think this example demonstrates that sometimes we try too hard, and perhaps this construct isn’t a great idea for Java. The “classic” approach is easily more expressive:

assertTrue(name.contains("Langr") && name.startsWith("J"));

or better…

assertTrue(name.contains("Langr")
assertTrue(name.startsWith("J"));

or even…

assertFirstInitialAndLastName(name, "J", "Langr");

I suppose my complaint could be tempered with the fact that these kinds of compound assertions don’t occur so frequently.

Yes, sure, the failure messages are better. That’s not significant to me, given that I don’t drive my development off of failure messages. Sure, all tests fail at least once, but I usually know why they’re failing the first time, so I don’t need that message initially. Later, when they fail for unknown reasons, more information might be useful (sometimes it is, not always), but if I need that, I just enhance the assertion I already have and rerun the tests. No big deal.

Writing custom “matchers” is also an example in ugliness, given the limitations of Java. (I need to speed up my move to Groovy or Ruby, so I can stop whining about Java so much…)

I won’t give up on the Java BDD tools completely, but I’m not much happier now than I was three or so years ago.

Atom