Functions & Methods in programming languages
Methods can be individually developed , tested and reused.
User of method does not need to know how the functions work.
A complete method:
specification+implementation
Specificatioon:Programming for communication
About "final"
declaring a variable final is a form of documentaion, a claim that the variable will never change after its initial assignment.
Why we nned to write specification?
- Remember them.
- Other people can read or change our programs only if they know them.
- different programmers on a team may have different specificaitons in mind.
Keep in mind:
- Communicating with the computer
- Communicating with other people: make the program easy to understand
Specification acts as a contract :
- the implementer is responsible for meeting the contract, and a client that uses the method can rely on the contract.
- Specifications place demands on both parties: when the specification has a precondition, the client has responsibilities too.
Specification acts as a firewall between client and implementor
Behavior equivalence
This part is easy to understand.
Precondition & postcondition
If the precondition holds for the invoking state, the method is obliged to obey the postcondition by returning appropriate values.
Translation:如果前提条件对调用的状态成立,方法就有义务遵守后置条件,返回适当的值。
If the precondition does not hold when the method is called , the implementation is not bound by the postcondition, which means it is free to do anything.
Stronger specification or waker?
A specification S2 is stronger than or equal to a specification S1 if
- S2 ’s precondition is weaker than or equal to S1 ’s
- S2 ’s postcondition is stronger than or equal to S1 ’s, for the states that satisfy S1 ’s precondition.