This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
In my book, I mentioned defensive programming in light of Design by Contract (DbC).
Design by Contract (DbC)
The notion of contract relates to obligations and benefits. An obligation to one party (supplier) is a benefit to another party (client).
In programming, contract is translated to precondition and postcondition.
Precondition > Process > Postcondition
The following can be observed from DbC:
- the stronger the precondition, more work for the client
- the stronger the postcondition, more work for the supplier
The following assumptions can be made when error occurs,
- Error in runtime is an indication of a bug
- A precondition error is a bug in the client
- A postcondition error is a bug in the supplier
The benefits of DbC is that there is less programming involved – you get more, you check less. There is less redundancy and there is clear separation of responsibility. Both client and supplier knows exactly their boundaries. DbC also contributes to software reliability and testability. It also results to clear documentation and easy debugging.
As opposed to defensive programming, you always check for precondition, you always validate inputs anywhere they appear. You’re checking things blindly just in case. This style leads to a lot of redundancy and code bloat. Everyone is responsible yet no one accepts responsibility.