- **Epistemic status:** #evergreen ![[Pasted image 20220803105419.png]] Design By Contract (DBC) is a [[Modularity]] technique for designing software coined by Bertrand Meyer when designing the language Eiffel. Software engineers define formal, precise, and verifiable specifications for software modules to ensure [[Computer Program]] correctness. The metaphor originates from business life. The specifications are referred to as “contracts” because it is the set of rights and responsibilities that the caller or “client” and the routine or “supplier” agree on. The obligations are classified as follows: - **Preconditions:** What must be true to execute a certain section of code or call a routine, in other words, is the routine's requirements. It is the responsibility of the caller to pass good data. - **Postconditions:** What must be true after the execution of a certain section of code or a routine that was called, in other words, is the routine's result. - **Class Invariants:** A logical assertion that is always held as true from the perspective of the caller when executing a routine. This means that when the caller gives the routine a certain property with a data type, the routine is expected to continue using that data type at the beginning of the execution process and at the end. The contract is equivalent to the Hoare triple that formalized the obligations, summarizing them into 3 questions software engineers must answer: - What does the contract expect? - What does the contract guarantee? - What does the contract maintain? Therefore, it can be read as follows: > If the routine's preconditions are met by the caller, that routine guarantee's that all postconditions and invariants will be true when it completes. If either party fails to uphold the terms of the contract, then a remedy is invoked that was previously agreed upon. A failure to uphold the terms of the contract is a [[Software Bug]]. When implementing this technique, The Pragmatic Programmer advises being strict on what will be accepted before the routine is executed and promise as little as possible as a return. --- ## References - “Design by Contract.” In _Wikipedia_, June 23, 2022. <https://en.wikipedia.org/w/index.php?title=Design_by_contract&oldid=1094674999>. - “Invariant (Mathematics) - Wikipedia.” Accessed August 3, 2022. <https://en.wikipedia.org/wiki/Invariant_(mathematics)#Invariants_in_computer_science>. - “Postcondition.” In _Wikipedia_, December 22, 2021. <https://en.wikipedia.org/w/index.php?title=Postcondition&oldid=1061639236>. - “Precondition.” In _Wikipedia_, June 16, 2022. <https://en.wikipedia.org/w/index.php?title=Precondition&oldid=1093466937>. - Thomas, David, and Andrew Hunt. _The Pragmatic Programmer, 20th Anniversary Edition: Journey to Mastery_. Second edition. Boston: Addison-Wesley, 2019.