Thursday, December 18, 2008

Preconditions, Postconditions, Invariants : Design by Contract for Java #2

Recently I wrote about how to apply "Design by Contract" with Java. I proposed to use the assert statement of java, in case you do not want to set up some external tools like Contract4J, iContract or Jass. After using the assert statement for a while I would recommend to use your own implementation of assertions instead like this:
public class Assertion {

 /**
  * Precondition.
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Require(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Precondition: The expectation '" + description + "' is violated");
     }
 }

 /**
  * Precondition.
  * @param objectToBeTested is an object we expect to be not null
  * @param objectName is the name of the variable we test.
  */
 public static void RequireNotNull(Object objectToBeTested,String objectName) {
     if (objectToBeTested == null) {
         throw new RuntimeException("Precondition: The expectation '" + objectName + " is not null' is violated");
     }
 }

 /**
  * Postcondition.
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Ensure(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Postcondition: The expectation '" + description + "' is violated");
     }
 }

 /**
  * Common condition to be used in the middle of methods
  * @param condition we expect to be true.
  * @param description repeats the condition or describes it in
  * other words.
  */
 public static void Check(boolean condition, String description) {
     if (!condition) {
         throw new RuntimeException("Condition: The expectation '" + description + "' is violated");
     }
 }
}
Why is the own implementation better than the assert statement?
  1. It does not make sense to switch off the runtime checks of assertions. We use assertions to simplify and avoid the error handling code in our methods. When it is possible to switch of assertions we loose this advantage, because we have to prepare our code to handle situations where the assertions are not checked.
  2. We are not only profiting from assertions during development and testing but also when the software is deployed. Assertions uncover error conditions much clearer and with better error descriptions. The logs in a production system will contain the messages from assertions and will help to find the cause of the problem much faster. If we switch off the assertions the problems will occurring much later and the cause of the problem can only be found with much more effort,
You can find details about "Design by Contract" in the famous book Object-Oriented Software Construction by Bertrand Meyer.

Monday, December 15, 2008

Mocking an object with two interfaces

Currently I spend a lot of time with maintaining 'legacy' java code. That is not really funny :-(. To make the most out of it, I write as much unit tests as possible to gain some more confidence in the code and be prepared for future bugfixes and refactorings. I stumbled over a small problem, when I tried to mock an object which implements two interfaces. My 'system under test'(SUT) class TextManager uses an object which is an IReader and an IWriter at the same time. The object is only handed over once and the TextManager has to cast the IReader object into an IWriter object. The whole design is not really outstanding (to be polite) and I would have implemented it myself a little bit different.
public class TextManager {
   
   private IReader reader;
   
   public void readAndWrite() {
      String text = reader.read();
      text = "*" + text + "*";
      ((IWriter)reader).write(text);
   }
}
I wrote a unit test for the readAndWrite() method and recognized that I can't simply create a jMock object for the IReader/IWriter object. My colleague Henning found a simple an effective solution. In my test package I create a new interface called IReaderWriter which extends IReader and IWriter. Now I can create a mock object for this new interface which is able to work as a test double inside TextManager:
public void testReadAndWrite() {
    
    // Setup
    final IReaderWriter mock = context.mock(IReaderWriter.class);
    TextManager textManager = new TextManager(mock);
    context.checking(new Expectations() {{
        one(mock).read(); will(returnValue("test"));
        one(mock).write("*test*");
    }});
    
    // Exercise
    textManager.readAndWrite();
    
    // Verify
    context.assertIsSatisfied();
}

Thursday, November 27, 2008

Preconditions, Postconditions, Invariants : Design by Contract for Java

In his famous book Object-Oriented Software Construction Bertrand Meyer described a design technique called "Design by Contract" (DBC) which can improve software quality dramatically. His programming language Eiffel supports this design technique inherently. This valuable technique is universal and widely accepted and can be used regardless in which programming language you are developing. To apply this technique in Java you need to define and execute assertions at runtime. The pre-, and postconditions of a method should also be part of the javadoc documentation.

There are a lot of tools and framework which help you to apply DBC to your Java code. For example OVal, Contract4J, which are using AspectJ, iContract or Jass, which are using a preprocessor for Java.

In some circumstances it might be too much effort to apply one of these tools to you development project. Luckily there was a rudimentary support for testing assertions added to the Java language starting with release 1.4. The assert statement allows to define runtime checks inside your code. With some simple conventions you can benefit from DBC without heavy tool support. Here is an example how to use the assertion mechanism of Java to apply "Design by Contract":

/**
* Is the editor in the edit mode?
* @return True, if the editor is in the edit mode. Otherwise false.
*/
public boolean isInEditMode() {
 ...
}

/**
* Sets a new text.
* Precondition: isEditMode()
* Precondition: text != null
* Postcondition: getText() == text
* @param name
*/
public void setText(String text) {
 assert isInEditMode() : "Precondition: isInEditMode()";
 assert text != null : "Precondition: text != null";

 this.text = text;

 assert getText() == text : "Postcondition: getText() == text";
}


/**
* Delivers the text.
* Precondition: isEditMode()
* Postcondition: result != null
* @return
*/
public String getText() {

 assert isInEditMode() : "Precondition: isInEditMode()";

 String result = text;

 assert result != null : "Postcondition: result != null";
 return result;
}

So you can use "Design by Contract" effectively with three simple rules:

  • Use the assert mechanism of Java to check preconditions, postconditions and invariants at runtime.
  • Describe each assert with a string that starts either with "Precondition:", "Postcondition:" or "Invariant:" followed by the textual description of the assert expression.
  • Add each assert description string to the javadoc comment of the method
We can get a little more support, when we write our own pre- and postcondition class:
public class Assertion {

   /**
    * Precondition.
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Require(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Precondition: The expectation '" + description + "' is violated");
       }
   }
  
   /**
    * Precondition.
    * @param objectToBeTested is an object we expect to be not null
    * @param objectName is the name of the variable we test.
    */
   public static void RequireNotNull(Object objectToBeTested,String objectName) {
       if (objectToBeTested == null) {
           throw new RuntimeException("Precondition: The expectation '" + objectName + " is not null' is violated");
       }
   }

   /**
    * Postcondition.
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Ensure(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Postcondition: The expectation '" + description + "' is violated");
       }
   }

   /**
    * Common condition to be used in the middle of methods
    * @param condition we expect to be true.
    * @param description repeats the condition or describes it in
    * other words.
    */
   public static void Check(boolean condition, String description) {
       if (!condition) {
           throw new RuntimeException("Condition: The expectation '" + description + "' is violated");
       }
   }
}
Using this class instead of 'assert' has the advantage that we can't forget to switch on the runtime checking of the assertions with -enableassertions. But keep in mind you still have to add method comments for the assertions. This is important, because the assertions should help the users of your class without forcing them to read your implementation details:
/**
* Sets a new text.
* Require: isEditMode()
* Require: text != null
* Ensure: getText() == text
* @param name
*/
public void setText(String text) {
 Assertion.Require(isInEditMode(),"isInEditMode()");
 Assertion.RequireNotNull(text, "text");

 this.text = text;

 Assertion.Ensure(getText() == text,"getText() == text");
}


/**
* Delivers the text.
* Require: isEditMode()
* Ensure: result != null
* @return
*/
public String getText() {

 Assertion.Require(isInEditMode(),"isInEditMode()");

 String result = text;

 Assertion.Ensure( result != null, "result != null";
 return result;
}

There is also an article "Using Assertions in Java Technology" on the Sun Developer network. See "Preconditions, Postconditions, Invariants : Design by Contract for Java #2" for further infos.

Tuesday, October 28, 2008

CruiseControl, ClearCase and Dynamic Views

When I set up CruiseControl in our development infrastructure, I struggled a little bit with the ClearCase integration. I got a lot of information from the very good book Kevin A. Lee: IBM Rational(R) ClearCase(R), Ant, and CruiseControl: The Java(TM) Developer's Guide to Accelerating and Automating the Build Process. Unfortunately the book is not explicit whether to use dynamic or snapshot views in conjunction with CruiseControl. In our project most of the developers are using dynamic views to set up their private workspaces. So I tried to use dynamic views as well for CruiseControl. That was not a brilliant idea. Whats the problem? When I set up CruiseControl as a windows service, I put the CruiseControl configuration file 'config.xml' into ClearCase. I recognized that the dynamic view with the 'config.xml' is not accessible by the service. Dynamic views have to be started with a cleartool command and then are mapped as drives. That must happen before the windows service is started. That seems not an straight forward solution when you are using the Java Service Wrapper. Also mapped drives are not accessible by a windows service as long as no user is logged on. You can't use the drive letter, instead you have to use an URL. In the end it was much easier to set up CruiseControl with a snapshot view.

Tuesday, August 26, 2008

TDD and Layered Architecture

I just read the blog post of Jeffrey Palermo about the Onion Architecture (see also the similar pattern Hexagonal architecture). Aspects of this patterns are used in an architecture our team defined for a healthcare information system.

Interesting is Jeffrey's rationale for moving certain components to the outer layer: The "infrastructure is pushed out to the edges where no business logic code couples to it", because "this code is most likely to change frequently as the application goes through years of maintenance". I think this is absolutely true.

Eric Evans presented a pattern called Layered Architecture in his book Domain-Driven Design: Tackling Complexity in the Heart of Software. His rationale for for moving certain components to the outer layer: The domain model should be separated from the technical details so it contains only the concepts we want to discuss with the domain experts. That is also a very good guideline when we have decide in which layer a certain piece of code belongs.

A third rational for moving certain components to the outer layer we get when we are using TDD: All components which can't be tested by pure unit tests should be placed on the outer layer. These components should be as thin as possible, because we want to test as much code as possible by pure unit tests. Components which do not have an API defined in the implementation language like GUI components, Windows Services, Wrapper to other languages and platforms and so on are candidates for the outer layer. Here we can't use pure unit tests. Slower or more awkward tests type have to be used. Data access components for databases contain or generate SQL statements. These data access components should be tested in conjunction with the real database to verify the correctness of the SQL statements. I call these tests database unit tests. They are much slower than the pure unit tests.

Friday, July 25, 2008

Configure CruiseControl Logging

If you have problems to get your CruiseControl running you may want to see some more log output. For example when your < modificationset> configuration does not work as expected, you want to see which commands are submitted for retrieveing the modifications in your source code repository. To switch on more log output create a log4j.properties file and place it in the CruiseControl folder side by side with the CruiseControl.bat and the config.xml file. The file may contain a log4j configuration like:
# Set root logger level to ERROR (default)
log4j.rootLogger=ERROR, CONSOLE, FILE
log4j.logger.net.sourceforge.cruisecontrol=INFO
log4j.logger.net.sourceforge.cruisecontrol.sourcecontrols=DEBUG

# A1 is to console
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d [%-9t] %-5p %-14.14c{1}- %m%n

# FILE is file logger with rotation
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.ConversionPattern=%d [%-9t] %-5p %-14.14c{1}- %m%n
log4j.appender.FILE.File=cruisecontrol.log
log4j.appender.FILE.MaxFileSize=5000KB
log4j.appender.FILE.MaxBackupIndex=4
Modify the CruiseControl.bat which starts the CruiseControl build loop. Add the command line parameter "-Dlog4j.configuration=file:./log4j.properties" to the call of the java application:
set CCDIR=%~dp0

:checkJava
if not defined JAVA_HOME goto noJavaHome
set JAVA_PATH="%JAVA_HOME%\bin\java"
set CRUISE_PATH=%JAVA_HOME%\lib\tools.jar
goto setCruise

:noJavaHome
echo WARNING: You have not set the JAVA_HOME environment variable. Any tasks relying on the tools.jar file (such as "< javac>") will not work properly.
set JAVA_PATH=java

:setCruise
set LIBDIR=%CCDIR%lib

set LAUNCHER=%LIBDIR%\cruisecontrol-launcher.jar

set EXEC=%JAVA_PATH% %CC_OPTS% -Djavax.management.builder.initial=mx4j.server.MX4JMBeanServerBuilder -Dlog4j.configuration=file:./log4j.properties -jar "%LAUNCHER%" %* -jmxport 8001 -webport 8080 -rmiport 1099
echo %EXEC%
%EXEC%
With this setup you get more detailed output concerning the access towards the source code repository.

Thursday, May 22, 2008

A New xUnit Test Pattern

Inspired by the Gerard Meszaros book xUnit Test Patterns: Refactoring Test Code, I have written down a pattern, which I used already many times:

Own Library Interface

Also known as: 'Skin and Wrap the API' [Working Effectively with Legacy Codeby Michael Feathers]

How can we make a code testable, when the code depends on a library class, which can't be replaced by a 'Test Double'?

We write our own interface that exactly mirrors the API of the library class. In our system under test (SUT) we use the interface instead of the library class itself.

The code we want to test is the system under test (SUT). It references a depended-on component (DOC) library class.

Some library classes do not inherit from an interface, they do not declare their methods as virtual or they provide static methods, so it is not possible to introduce a Test Double to the SUT via Dependency Injection or Dependency Lookup to replace the library class during testing. This problem arises very often when we need to use system or third party libraries (like the .NET framework) where we can’t modify the library classes and have to use them as they are. Library designers prefer to use class-based APIs instead of interfaces, because they can be evolved in later versions of the library. If they want to add members to a library interface in a later version , they would break existing code [Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Librariesby Abrams and Cwalina]. Very often the SUT can’t be tested together with the library class, because the library class can’t be used in the test environment. The reason may be that the library class will not return values needed for the test or executing it would have undesirable side effects.

How it Works

We write our own interface which mirrors the API of a library class we are using in our SUT. Our own interface does not need to contain the complete API of the library class but may contain only the subset we are requiring for our SUT. We implement a thin wrapper for the library class which inherits from our own interface. The wrapper will contain no logic. Each method can simply be forwarded to the library class, because the signatures of our own interface are the same as the library class. The SUT must use the interface instead of the library class itself. The SUT will be initialized with a concrete object via Dependency Injection or Dependency Lookup. In the production environment the thin wrapper is used. In the test environment we can replace the thin wrapper with a Test Double.

When to Use It

We have to use the Own Library Interface when we use a third party library class in our SUT which has both of the two following characteristics:
  • The dependency on the library class prevents us from executing the SUT in a test environment. It may be plain impossible, too slow, too complex or too expensive to prepare a test environment for testing the SUT together with the library class.
  • The library class can not be replaced by a Test Double, because it does not inherit from an interface, it does not declare its methods as virtual or it has static methods.
These circumstances very often lead to the smell Developers Not Writing Tests. The SUT will be declared as untestable. Also TDD beginners often stumble over this problem and get the impression that TDD is not applicable to real world examples.

Implementation Notes

Library classes which define the API for operating system mechanisms (registry, event log, services), the API for hardware sub systems (network infrastructure) or the API to other software components (SMTP server, POP3 server) are candidates for the usage of the Own Library Interface pattern. Preparing a fixture for testing own classes which are using such library classes may be plain impossible, too slow, too complex or too expensive. See TDD for Beginners as an detailed example for the usage of the Own Library Interface pattern. We do not need to use the Own Library Interface pattern, when we can test our SUT together with the library class. For example the File or Directory classes from the .NET framework can easily be tested together with the SUT, because preparing files and directories during test setup as well as checking them after exercising the SUT is quite easy.