Monday, March 19, 2012

Agile programming in extremis

I was recently working on a project with a team that had adopted Agile development methods with a vengeance.  In the next few posts, I'll report on the evolution of some code during repeated refactorings.

To protect the innocent and obscure the guilty, I am paraphrasing the actual code and omitted some of the boilerplate and other detail, but rest assured that Dave Barry would agree that "I am not making this up."

To get started, here is the original code.  There are two files. Before I formatted it for this blog it containing 23 lines of production code and around 50 lines of test code (of which 23 are shown here.)

public class EventListener{
  static final int X_LIMIT = 200;
  static final int Y_LIMIT = 200;
  static final long TIME_LIMIT = 500L;

  private final DuplicateEventHandler duplicateEventHandler;
  private Event previousEvent = null;
  
  public EventListener(
         DuplicateEventHandler duplicateEventHandler){
    this.duplicateEventHandler = duplicateEventHandler;
  }
  
  public void onEvent(Event currentEvent)
  {
    if( previousEvent != null &&
       (math.abs(currentEvent.getX() – previousEvent.getX()) 
          < X_LIMIT) &&
       (math.abs(currentEvent.getY() – previousEvent.getY()) 
          < Y_LIMIT) &&
       (currentEvent.getTime – previousEvent.getTime() 
          < TIME_LIMIT)) {
       duplicateEventHandler.handleSameEvent(currentEvent);
    }
    previousEvent = currentEvent.cloneEvent(); 
  }
};

public class EventListenerTest{
  private EventListener testObject;
  
  private Event event1 = new Event(parameter);

  @Mock
  private DuplicateEventHandler duplicateEventHandler;

  @Before  
  public void setup(){
    testObject = new EventListener(duplicateEventHandler);
    testObject.onEvent(event1);
  }    
  
  @Test
  public void thisIsATypicalTest(){
    Event event2 = new Event(various parameters 
           to test boundary conditions);
    testObject.onEvent(event2);
    verify(duplicateEventHandler).handleSameEvent(event2);
    // or depending on the parameters to event2...
    verify(duplicateEventHandler, never()).handleSameEvent(
       event2);
  }
};
If you are a programmer, now would be a good time to examine the code above and decide what changes, if any, you would make to improve it.

No comments: