Contracts With special reference to RabbitHunt Multi-person projects • Except for coursework, it is rare for a single person to write an entire program • Each programmer has to know what the other programmers are doing • In addition, each programmer has to let the others know what he/she is doing, BUT • In order to maintain control of code, it is necessary to hide details of the implementation Contracts • A contract specifies the rights and responsibilities of each party to the contract • In programming, a contract spells out what other programmers are allowed to depend on in my code • When I write a contract, I have these responsibilities: – I must provide enough information so that others can make use of my code (my classes and methods) – I must not arbitrarily change what I offer • I also have these rights: – I can change the code however I like, so long as it continues to meet the terms of the contract – I can provide additional functionality javadoc • In Java, the javadoc comments (or just “doc comments”) typically provide the contract • In BlueJ, you can see the doc comments by choosing Interface from the pull-down menu in the upper-right corner • If you have not read “The contract” portion of the RabbitHunt assignment, you should do so • Rule 89, “Program by contract,” is also relevant The RabbitHunt contract • What is most important about the RabbitHunt contract is the information I do not provide: – I provide a number of constants, such as Model.N, Model.MIN_DIRECTION, and Model.FOX, but I do not specify the numerical values of those constants – I did not specify the size of the field, instead I provide the additional constants NUMBER_OF_ROWS and NUMBER_OF_COLUMNS • It is important to know both: – What you can depend on to remain the same – What you cannot assume will remain the same Magic numbers • A magic number is a constant (such as 20) that appears, sometimes without explanation, in the code • Magic numbers are poor style • Named constants, such as NUMBER_OF_ROWS, have two advantages: – They provide some documentation for the meaning of the constant – If you decide to change the constant, you need only do so in one place rather than many • Numbers that “everybody knows” and that “never change” are not usually considered to be magic – However, adding or subtracting 1 will make it “magic” – Example: for(int day = 0; day < 8; day++) { ... } • Zero and one are typically not considered to be magic numbers Summary • In the “real world,” programmers almost always work in teams – You have to let others know how to use your code – You cannot afford to guarantee you will never change your implementation – You need to know how to use other people’s code – It’s dumb to depend on the details of their implementation • It’s important to distinguish interface from implementation – Programs that are too interdependent are hard to change – Programs that cannot be changed are doomed The End