liveBook · Manning

Programming by contract

As explained in Functional Design and Architecture: Examples in Haskell

A software-design technique that expresses behavioral contracts explicitly and checks implementations against them.

Programming by contract makes a subsystem’s behavioral rules explicit and checks implementations against them. Without defined failure behavior, exceptions, global state, missing files, or memory problems make client code unpredictable. section 1.4.3

A lamp contract violation

An ILampSwitcher client should switch every lamp transparently. DaylightLamp follows that expectation, but TableLamp throws an exception after switching, breaking code that relies on the shared contract. The implementation must define and follow its promised behavior. section 1.4.3

Listing 1.6 Concrete lamp code
class DaylightLamp (n: String, v: Int, onOff: Boolean)  #1
  extends ILampSwitcher {
    var isOn: Boolean = onOff
    var value: Int    = v
    val name: String  = n
    def switch(onOff: Boolean) = { 
      isOn = onOff
    }
}
  
class TableLamp (n: String, onOff: Boolean)             #2
extends ILampSwitcher {
  var isOn: Boolean = onOff
  val name: String  = n
  def switch(onOff: Boolean) = {  
    isOn = onOff
    // Debug: will remove it later!
    throw new Exception("switched")                     #3
  }
}

Inspect the concrete lamp implementation to see how an otherwise compatible switch operation violates its client-facing contract. section 1.4.3

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Defines explicit contracts and illustrates a violation, but does not detail a specific contract-checking tool or formal notation.
Examples
Uses ILampSwitcher, DaylightLamp, TableLamp, exceptions, global state, absent files, and memory operations as contract cases.
What it assumes
Assumes familiarity with object-oriented classes, interfaces, implementations, and client code.
What you can do after
Diagnose implementations that violate client-facing behavioral contracts and recognize why substitutions become unsafe.
How it connects
Connects behavioral contracts with interfaces, Liskov substitution, SOLID principles, and object-oriented design.

Also explained in

Compare how 3 books explain programming by contract →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.