bennettscash
bennettscash
DBC vs. TDD Part 1 - Design By Contract
Thursday, 9 October 2008
I’ve just finished reading ‘The Pragmatic Programmer’, which has one section devoted to the merits of Design By Contract. I came out of university four years ago with the idea that DBC was A Good Thing, and was using it for around six months before I began supplementing it with Test Driven Development techniques. This gradually turned into using TDD and forgetting all about DBC. Reading The Pragmatic Programmer has made me think about this in more detail, and made me wonder whether Design By Contract even has a place in software engineering now that TDD has become well-known and is fairly widely used.
This is the first of three articles where I wanted to explore this idea, find out what you think, and see what conclusions I end up reaching. This article goes into Design By Contract - What it is and why we might choose to use it. The second will cover similar aspects of Test Driven Development; with the third article comparing the two to see where they intersect and what (if anything) is offered by one technique but not the other.
So, let’s get started with Design By Contract.
Each piece of functionality you write has a ‘contract’ specifying what must be true when the method is called, and one specifying what will be true after the method has completed provided the initial contract is satisfied by the caller.
A class may also have a ‘class invariant’ specifying things that will remain true throughout the existence of a particular class instance.
The notion is that, before you start coding, you step back and think through which situations your method should operate in, and which it should not. Then you write these down as your initial contract. Next you think about what will be true upon completion of your method and write this down. These contracts might be automated or they might not be, that doesn’t matter. The point here is that you have documented all conditions your method must be successful in, and all conditions your method must satisfy upon completion.
Once you begin actually implementing your method you then have a reference point to look back on to ensure that you do everything you need to for all the conditions you need to cater for. This ensures that we’re focusing on what we need to be focusing on, acting as a verification and validation mechanism while we’re coding.