Lots of discussion about Design by Contract has been floating around, most of which I agree with.
Using “asserts”, etc., in code is defensive programming. Anything which checks that your classes are polite to one another is defensive; tests should pick these kind of problems up.
Wouldn’t it be nice, though, if you could easily design the things which use your DbC classes in such a way as to ensure that they adhere to the contract specified by the class that they’re using?
I’m thinking of something which sets up mock objects so that whenever a particular method call is expected and no constraint is supplied, it can look up a registered set of constraints.
So for instance, in my Tetris-clone, I would set up all my mocks of the Game interface to ensure that the size of game board created was always > 4 x 4 (the smallest square which all tetris blocks can occupy). I would do this before I actually created any Game implementations, while designing the Engine – it’s part of the Engine’s behaviour that it should never create a silly size of game.
Not sure how this would work, but it has a number of bonuses:
– it isn’t defensive programming, just another form of behaviour driven design
– it allows behaviour / test driven design to specify design by contract, before any classes exist which can actually implement asserts or any other checks
– it makes me think about the behaviour of the classes using the Engine too, since they need to behave themselves in order for the Engine to behave.
In fact, I reckon if I were to include classes called, say, “MockGame”, which mocked and added these constraints to some kind of mandatory expectation / constraint map… maybe that would work…
Let me sleep on it.