Chapter 8. Contract, Contract, Contract!

What does it mean for software to have a contract? There turns out to be no hard-and-fast answer to that question. It can mean something very formal in some situations. Some programming languages such as Eiffel have raised the notion of a software contract to the level of a first-class language feature (meaning that the ability to define a complete contract is part of the language). In other languages, contracts have to be defined in less formal ways. Is it possible to write software without a contract? Not really. It is, however, possible to write software with a poorly defined or misunderstood contract.

In the simplest terms, having a contract means promising to do something. Software can have contracts that are explicit or implicit. The more explicit your contract is, the easier it will be for people who consume your software. Having an explicit contract means communicating in no uncertain terms what your software will do, and promising to do it. Implicit contracts are often defined by class/property/method names. Let's take a look at a Calculator class:

namespace ContractsInCSharp
{
    public class Calculator
    {
        public double Add(int op1, int op2)
        {
            return op1 + op2;
        }

        public double Divide(int divided, int divisor)
        {
            return divided / divisor;
        }
    }
}

In this case, the Calculator class establishes an implicit contract through naming. The name Divide implies a division operation, and since its arguments are named divided and divisor, you can ...

Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.