Category Archives: Object Oriented Design

Designing inter-object protocols using mocks

The intent of my recent paper, was to demonstrate how mock objects could be used to discover roles, and design the communication protocols between objects. The following content did not make it to the final version, I think these are important points so i will describe them here.
Distinguish between an Object’s Internals and its Peers
It is important to distinguish what the internals of an object are and who are its peers that it communicates with.  An object’s internals are usually created and used within an object. In my example the fact that the Register object collaborates with the Sale object to calculate the receipt total is hidden. Peer objects, on the other hand, aren’t hidden inside the object, they are a passed in to the object, either through the constructor as a dependency or through a setter (if the peer object is a policy or notification object).
All interactions internal to an object should be hidden from the client code that uses the object; likewise a unit test should not be concerned with the internal details of the object under test.
Exposing an objects internals details to simply test every aspect of a class in pure isolation, causes the tests to be overly coupled to the implementation details of the object. You will find tests using mock objects highlight these design issues very quickly, one hint is when you find that the production code, simply mirrors the expectations you wrote in the test code, this  obviously makes tests very brittle since they overly coupled to the implementation details of the object under test.
This could be addressed by changing the behavior of the mock framework to ignore all calls between the object under test and its collaborator unless explicitly specified.  However this does not address the underlying weakness in the design of the protocol between the object under test and it collaborators, it fact it simply hides all complex inter-object protocols.
Nat Pryce coined the phrase “A composite object should be simpler than the sum of its parts.”  An object should provide a simpler API to its clients, rather than simply exposing all its internal objects through its API. I find this is a good heuristic to follow when deciding what should be internal to an object and what its peers should be. On the other hand we should ensure we are not hiding the wrong information inside an object. Well-designed objects should be context independent and not tied to its environment; objects tightly coupled to its environment will be difficult to instantiate in a unit test. I find the rapid feedback provided by tests is invaluable when designing objects.

Why did I chose to use NMock ?

A lot of people ask me why i chose NMock, for this introductory article, I felt NMock 2 is the best choice of API,  because it works best within the context of the article. It has an expectation-based API, which makes designing object communication the focus of testing. Its expectation API acts as a domain specific embedded language that clearly, precisely, and declaratively describes object communication. I also find that NMock2 provides a highly detailed explanation of what has failed, which allows for quick error diagnosis and resolution.

I’m sure many people will have different opinions on this but I have avoided using mock frameworks that use the popular Arrange, Act, Assert (AAA) style because I find that it does not get you started off by thinking about the contracts or communication protocols between objects. With AAA-style mocks I find it’s easy to overlook design flaws in your inter-object communication.

The main drawback of NMock is the use of strings to identify expected methods makes refactoring harder.  This becomes less of an issue when a code based is designed around well-defined roles and responsibilities, containing narrow role based interfaces, which are used more locally.


Object Persistence ??

In software development, programming only represents half the problem, the other problem is storing and sharing data across users and other programs. The Object oriented paradigm expands the meaning of “data”. Object contains methods, complex data structures and references to other objects. This can’t be easily stored in a relational Database.

Although it is possible to store objects in a relational database, we can’t overlook the underlying conceptual differences between the relational and object paradigm. This is common know as the impedance mismatch .

we can define objects in terms of classes and create hierarchies of these classes, now to effectively store objects, a database must be able store inheritance hierarchies and create instances of these classes using this information. Relational database were never designed to handle hierarchical structures like this. As Developers we spend a lot of time to work around these limitations to try and make it all fit, knowing very well there is an obvious  underlying mismatch. Let take a very trivial example, suppose we have an Address class which was mapped to an Address Table. Now suppose there was a requirement to handle new types of address which contained an additional field. On the object level we could create a subclass of Address and define an extra variable to hold this additional field. Now on the relational database we would typically create another table to hold this additional information with a link to the Address table. Now this requires construction an object from multiple tables, now as the object structure get complex this can be very time consuming.

Most object oriented designs contain composite objects and usually there are complex patterns of interaction between these objects. Objects hold reference to other objects, to allow fast navigational access. Relational databases on the other hand can also handle these nested structures but they have no references so navigational access is not possible but they have is associative access which based on matching data, this process is very slow and depending on the complexity of the nested object structures, this can be a time consuming process. A study done by the US navy showed relational database are 100 to 1000 times slower than a database that can provide navigational access.

As mentioned before the object paradigm expands the meaning of “data”, one of the fundamental characteristics of Object Oriented design is encapsulation. Objects contain methods as well as data, this means storing methods and data as one package and maintain cohesion between the two. Generally relational database cannot support this, relational databases have stored procedures but this is usually programmed using Sql (Original intent of SQL was never intended for programming but to be used by the end user). This is always different to the programming language used to implement the objects.

In my opinion relational database introduces barriers to object thinking, objects allows us to think in terms of real objects such as customer, products, items. When they are stored in a relational database they are dissembled into different tables. rather than thinking about the domain model, we try to design our object model so they can be chopped up later into some low level data which bears little resemblance to the original object just so they can some how fit into a relational database. This is the same as having to disassemble your car every time you wanted to park it in your garage. Not only that you stored each part in a different garage, you have a garage where every body put there car wheels, another garage where every one stored their car body. And when you want to use your car again in the morning, you had to go to each garage identify the part that belong to your car, then assemble it before you can drive your car again, how painfully inefficient, but this is essentially what happened when we store Objects in a relational database.

O/R mapping are great for some problems (check out GLORP) but really they don’t solve the underlying impedance mismatch problem, it might insulate the mapping from the developer to a certain extent, but really you still disassembling your car before parking in the garage, its just being done by someone else.

Can a Object Oriented Database provide the perfect solution ?

Object Oriented or Class Oriented Design?

Its been over 40 years since object orentation as a programming pradigm started in Norway when Kristen Nygaard and Ole-Johan Dahl invented the language Simula . Now a days most software is describe their work using some sort of object vocabulary and or use an OO language. However the ubiquity of object oriented languages does not mean, in experience most developers aren’t getting the full leverage out of object technology. Object orientation is a programming paradigm you can design object oriented software and implement it using almost any programming language, of course some languages offer you more support than others, conversly you can implement your software with a very non object oriented implemetation using an ‘Object Oriented Language’ such C#, Java or even Smalltalk. Object oriented design and object thinking trancends programming languages. So it not the tools or programming language you use to implement the software, but its the way you think about a design. Thinking in objects is the key to leveraging the most out of object technology to create elegantly designed software. Trygve Reenskuag creator of the MVC pattern, and the creator of the OORAM software Engineering Method comments that programming languages are class oriented rather than object oriented, thats why most of us end up thinking and modelling in terms of classes rather than objects. A Class is powerful abstraction to implement objects, but its inadequate for modelling and thinking about objects, because a Class is static, it is defined at build time, objects on the other hand are dynamic.

Objects vs Classes

It’s important to understand the difference between a class and an objects, I remember when I was at university learning C++ people used the term class and objects interchagably, it is key to distintguish between the two. A class can be viewed as template that defines a set of characteristics and behaviours an object will have, a class is also a factory which creates specific instances of objects that have these general characteristics and behaviours. In languages like Smalltalk a class is an object, that is responsible for creating instances of objects with a particular class of behaviours and charateristics.

Similarly it is important to distinguish between ‘Object thinking’ and ‘Class thinking’ when desgning Object Oriented software. Thinking and modelling a solution to a problem by thinking in terms of various classes rather than thinking of a group of objects working together, more often that not results in a implementation that is inelegant and rigid.

Object Thinking

David West has written an excellent book titled “Object Thinking” (I highly recommend this book to every developer). Thinking in terms of classes, focuses our attention on the solution space rather than the problem space. A class is very static by thinking in terms of classes our solution tends to be static and rigid, objects on the other hand are dynamic, by thinking in Objects we let the problem define our solution, which leads to modelling a more natural and elegant solution. Think about an object as “A virtual person that is capable of performing certain tasks. who has access to all the knowledge and resources required to complete its assigned tasks”. What we will have is a cooperating community of virtual persons interacting with each other to solve a problem. Thinking in terms of objects will lead to a closer match between your object model and the business model (the enterprise domain). Thinking in objects also helps us find the naturally occurring divisions and classifications in the problem space.

Consider the following example, there is a Club that has different types of members, GoldMember, SilverMember and StandardMember, all members have a name, address, date of birth etc, but each type of member has a different discount Rate.

thinking in terms of classes we usually come up with the following implementation, using class inheritance

Class Diagram

The above is a workable solution, but its kind of rigid. Suppose we have an object which is an instance of class SilverMember, think back to the ‘Object as a Person’ metaphor. suppose this virtual person (ie this object which is instance of SilverMember) wants to upgrade to a gold membership. What happends now ? with the above implementation you would have to create a new instance of class GoldMember. Class are static defined at build time, objects on the other had are dynamic, that is why it is important to think in terms of objects and the various Roles they play when modelling. In the real world all you would do is get a new gold membership card or something like that.

thinking along these lines we could come up with the following implemetation

Implemetation Using Object Composition

in this implementation we have a solution that uses object composition, a member object has a Membership object. In the above solution it trival to plugin different membership objects into the member object. so if a SliverMember wants to upgrade to a GoldMembership all we do is set member Objects membership property to an instance of GoldMemberShip and discard its old SiverMembership.

The above solution is example of the strategy pattern in action. Thinking in terms of objects and modelling in terms of the Roles the objects play, leads to a elegant solution.

To conclude object orientation is a pradigm, its a way of thinking. A Class is great and a powerful abstraction for the implementation of objects, so most OO programming languages are class oriented because they are all about implemention of computer programs. But for modelling and designing object oriented solutions it is important we think in term of objects and the Roles the objects play. Trygve Reenskaug has written numerous articles and an excellent book on role modelling