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


