Over a million developers have joined DZone.

OOP: Behavioural and Structural Constraints

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

A few months ago I wrote a post describing how we should test the behaviour of code rather than the implementation whereby we would write tests against the public API of an object rather than exposing other internal data of the object and testing against that directly.

While I still think this is a useful way of testing code I didn't really have a good definition for what makes that a test of an object's behaviour.

I've been reading through James Odell's 'Advanced Object-Oriented Analysis and Design Using UML' and he describes it like so:

Behavioural constraints limit the way object state changes may occur

In Meilir Page-Jones language I think this would describe informative and imperative messages:

  • Informative – a message telling an object about something that happened in the past.
  • Imperative – a message telling an object to take some action on itself.

Both of these types of messages change the state of the object so in C# or Java these would be the public methods on an object that clients interact with.

That seems to describe the way that we would test the object. These would be the methods that we'd call in our test.

Odell goes on to describe structural constraints:

Structural constraints limit the way objects associate with each other, that is, they restrict object state.

This seems close to an interrogative message:

  • Interrogative – a message asking an object to reveal something about itself.

This would seem closer to the way that we would verify whether the object's state changed as expected. We're querying the object through the structural constraints that have been setup.

I can think of two main reasons why this approach is more effective than just testing directly against the internals of an object:

  • It ensures we're testing something useful otherwise we might be writing tests on our code for a scenario that will never happen.
  • We have a better idea of when we've finished writing our tests since we know when we've tested all the behaviour.
From http://www.markhneedham.com

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}