Implementation by Contract

Implementation by Contract is a term not really coined yet, but we will use it for consistency purposes to keep the four necessary activities of programming - analysis, design, implementation and testing - complete. The core idea is based on conduction the TDD cycle on the implementation level:

  • focus on one test (red) at a time,
  • code the necessary method or methods to run that test successfull (green) and
  • refactor the class under test and - if nessary - the abstract data type (interface and interface contract) it implements without breaking that test (green).

Test per test the test case is turned from red to green following that iterative approach. This iterative implementation activity implements the abstract data type TimeOfDaySpec. The result is the target class TimeOfDay (complete listing):

package timeofday;

import de.vksi.c4j.ContractReference;
import de.vksi.c4j.Pure;

@ContractReference(TimeOfDayContract.class)
public class TimeOfDay implements TimeOfDaySpec {
   private int hour;
   private int minute;
   private int second;

   public TimeOfDay(int hour, int minute, int second) {
      setHour(hour);
      setMinute(minute);
      setSecond(second);
   }

   @Override
   public void setHour(int hour) {
      this.hour = hour;
   }

   @Override
   public void setMinute(int minute) {
      this.minute = minute;
   }

   @Override
   public void setSecond(int second) {
      this.second = second;
   }

   @Override
   public int getHour() {
      return hour;
   }

   @Override
   public int getMinute() {
      return minute;
   }

   @Override
   public int getSecond() {
      return second;
   }

   @Override
   public boolean isBefore(TimeOfDaySpec other) {
      boolean result;
      int seconds = 0;
      int otherSeconds = 0;
      seconds = getSeconds(this);
      otherSeconds = getSeconds(other);
      result = seconds < otherSeconds;
      return result;
   }

   @Pure
   private int getSeconds(TimeOfDaySpec tod) {
      int result = 0;
      result = tod.getSecond() + tod.getMinute() * 60 + tod.getHour() * 3600;
      return result;
   }
}

The implementation looks simple and clean. In fact it is, as we do not have any need for exception handling or guards in our methods.
It's the contract who protects our class. This will be seen in the next activity, Testing by Contract.