Design by contract and another item for the JBehave wish-list

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.

This entry was posted in Uncategorized. Bookmark the permalink.

5 Responses to Design by contract and another item for the JBehave wish-list

  1. icklemichael says:

    Not really following, probably ’cause I don’t know what jbehave is…

    In design by contract terms I’d have a Game interface which would look like (in my own special made up version of DBC pseudo java):

    interface Game {
        Game(int xSize, int ySize, Pieces[] pieces),
            requires {
                // Magic numbers are bad, mmm'k?
                assert(xSize >= 4);
                assert(ySize >= 4);
            }, ensures {
                for (int i = 0 ; i < pieces.length ; i++) {

    In real world java I’d have to separate this out into two interfaces, Game and GameFactory, so my GameFactory interface would look like:

    public interface GameFactory {
        public Game createGame(int xSize, int ySize, Pieces[] pieces);

    The way of enforcing my contract which immediately springs to my mind is by using a decorator:

    public class ContractedGameFactory implements GameFactory {
        private final GameFactory inner;
        public ContractedGameFactory(GameFactory inner) {
            this.inner = inner;
        public Game createGame(int xSize, int ySize, Pieces[] pieces) {
            assert(xSize >= 4);
            assert(ySize >= 4);
            Game game = inner.createGame(xSize, ySize, pieces);
            for (int i = 0 ; i < pieces.length ; i++) {
            return game;

    Then when we (or spring, or whatever) create our GameFactory they can always ensure it’ll have it’s contract enforced at run time.

    Isn’t that what DBC is about?




    Hmm.. Now I think maybe I see what you’re getting at, maybe. If I was enforcing my contract in my concrete GameFactory implementation, then my mocks would miss out on it, and potentially get away with shoving dodgy data through if my mocks weren’t adequately checking them.. And if they were checking them then that would be duplication, which would be bad.

    So you’re looking at some way of specifying and registering them individually so I could add my constraint with something like:

    registerConstraint(GameFactory.class, "createGame", new RequiresConstraint() {
        public void check(Object[] args) {
            assert((Integer)args[0].intValue() >= 4;
            assert((Integer)args[1].intValue() >= 4;

    Suppose this would only apply to ‘requires’ (apologies for using the eiffel terminology if the cool kids now do DBC in other languages), as ‘ensures’ wouldn’t really make sense on a mock…

    I can’t actually be following at all, ’cause none of this makes any sense in terms of mocking and behaviour.

    What are you talking about? If you could explain in terms of my simple contract (with code examples) that would be ideal! 🙂

  2. anonymous says:

    This is what OO-Matron does (

  3. sirenian says:

    You’ve got it, Mike. This is mostly for me so I can write it up properly later…

    I’m doing Test Driven Design (well, Behaviour Driven Design, which is similar but better because it reads like English). Check out the JBehave project at – it’s a bit like JUnit, but has some nifty additional features. Best of all, my non-IT boyfriend can read the methods… things like “TShape.shouldRotateRightSuccessfullyWhenNotBlocked()” instead of “TShape.testSuccessfulRotateRight()”.

    Anyway, back to the mocky problem:

    I create the Engine class, which uses the GameFactory, before I create the Game (or, in fact, the GameFactory).

    I need to be sure that I never pass the GameFactory a silly size of game to construct. I only have an interface of GameFactory – not its implementation, the SimpleGameFactory or ComplexGameFactory or whatever else I want. So I can’t actually put the Assert code in the factory.

    Normally, when I mock the GameFactory I do something like:

    Mock gameFactoryMock = mock(GameFactory.class);

    I can also add expectations to this, with constraints on the arguments of the expectations:

    gameFactoryMock.expects("createGame").with(new Constraint() {
      public boolean matches(Object[] args) {
        // What to put in here?

    So the “matches” method should say:

    return ((Integer)args[0]).intValue() > 4 && ((Integer)args[1]).intValue > 4;

    for all expectations of “createGame”, even ones where the constraint is additionally specified as “((Integer)args[0]).intValue() == 2” which would be stupid.

    JBehave comes with all kinds of MiniMockSugars and helper classes which might be ideal for dragging this kind of thing in.

    I shall have to check out OO-Matron and see what it does.

  4. sirenian says:

    Should be >= 4. But you get the idea.

  5. anonymous says:

    How spooky, the night before you blogged this I had a sleepless night thinking about some gnarly client problem I have. Later on during my semi-consciousness I was thinking about that very same thing – how you might plug a DbC metaphor into JBehave… I have no idea what got me onto that!

    And yes you should take a look at OO-Matron it to too contains all Syntactic Sugars you describe (and many more) to define DbC contracts.

    DarrenR (TW)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s