Category: Designing Contracts

  • Invariants

    We have seen that pre-conditions should hold before a method’s execution, and post-conditions should hold after a method’s execution. Now we move on to conditions that must always hold before and after a method’s execution. These conditions are called invariants. An invariant is thus a condition that holds throughout the entire lifetime of an object or a data…

  • Strong and weak pre- and post-conditions

    When defining pre- and post-conditions, an important decision is how weak or strong you want them to be. In the previous example, we handle the pre-condition very strongly: if a negative value comes in, it violates the pre-condition of the method, so we halt the program. One way to avoid halting the program due to…

  • The assert keyword

    The Java language offers the keyword assert, which is a native way of writing assertions. In the previous example, instead of throwing an exception, we could write assert value >= 0 : “Value cannot be negative.”. If value is not greater than or equal to 0, the Java Virtual Machine (JVM) will throw an AssertionError. In the following listing, I show a version of the TaxCalculator using asserts. Listing 4.3 TaxCalculator with…

  • Pre-conditions and post-conditions

    Going back to the tax calculation example, we need to reflect on pre-conditions that the method needs to function properly, as well as its post-conditions: what the method guarantees as outcomes. We already mentioned a pre-condition: the method does not accept negative numbers. A possible post-condition of this method is that it also does not return negative numbers. Once the…

  • Introduction

    Imagine a piece of software that handles a very complex financial process. For that big routine to happen, the software system chains calls to several subroutines (or classes) in a complex flow of information: that is, the results of one class are passed to the next class, whose results are again passed to the next…