Home > Articles > Programming > Ruby

  • Print
  • + Share This
From the Rough Cut Finding the Public Interface

Finding the Public Interface

Find and defining public interfaces is an art. It presents a design challenge because there are no cut and dried rules. There are many ways to create 'good enough' interfaces and the costs of a 'not good enough' interface may not be obvious for a while, making it difficult to learn from mistakes.

The design goal, as always, is to retain maximum future flexibility while writing only enough code to meet today's requirements. Good public interfaces reduce the cost of unanticipated change; bad public interfaces raise it.

This section introduces a new application to illustrate a number of rules-of-thumb about interfaces and a new tool aid to in their discovery.

An Example Application: Bicycle Touring Company

Meet FastFeet, Inc., a bicycle touring company. FastFeet offers both road and mountain bike trips. FastFeet runs their business using a paper system. They currently have no automation at all.

Each trip offered by FastFeet follows a specific route and may occur several times during the year. Each has limitations on the number of customers who may go, and requires a specific number of guides who double as mechanics.

Each route is rated according to its aerobic difficulty. Mountain bike trips have an additional rating which reflects their technical difficulty. Customers have an aerobic fitness level and a mountain bike technical skill level to determine if a trip is right for them.

Customers may rent bicycles or may choose to bring their own. FastFeet has a few bicycles available for customer rental and they also share in a pool of bicycle rentals with local bike shops. Rental bicycles come in various sizes and are suitable for either road or mountain bike trips.

Now that you have an overview of FastFeet, consider the following simple requirement, which will be referred to later as a use case: A customer, in order to choose a trip, would like to see a list of available trips of appropriate difficulty, on a specific date, where rental bicycles are available.

Constructing an Intention

Getting started with the first bit of code in a brand new application is intimidating. When you are adding code to an existing code base you are usually extending an existing design. Here, however, you must put pen to paper (figuratively) and make decisions that will determine the patterns of this application forever. The design that gets extended later is the one that you are establishing now.

You know that you should not dive in and start writing code. You may believe that you should start writing tests, but that belief doesn't make it easy. Many novice designers have serious difficulty imagining the first test. Writing that test requires that you have an idea about what you want to test, one that you may not yet have.

The reason that test-first gurus can easily start writing tests is that they have so much design experience. At this stage they have already constructed a mental map of possibilities for objects and interactions in this application. They are not attached to any specific idea and plan to use tests to discover alternatives, but they know so much about design that they have already formed an intention about the application. It is this intention that allows them to specify the first test.

Whether you are conscious of them or not, you have already formed some intentions of your own. The description of FastFeet's business has likely given you ideas about potential classes in this application. You probably expect to have Customer, Trip, Route, Bike and Mechanic classes.

These classes spring to mind because they represent nouns in the application that have both data and behavior. Call them Domain Objects. They are obvious because they are persistent; they stand for big, visible real world things that will end up with a representation in your database.

Domain Objects are easy to find but they are not at the design center of your application. Instead they are a trap for the unwary. If you fixate on Domain Objects you will tend to coerce behavior into them. Design experts notice domain objects without concentrating on them; they focus not on these objects but on the messages that pass between them. These messages are guides which lead you to discover other objects, ones that are just as necessary but far less obvious.

Before you sit at the keyboard and start typing you should form an intention about both the objects and the messages needed to satisfy this use case. You would be best served if you had a simple, inexpensive, communication enhancing way to explore design that did not require you to write code.

Fortunately, some very smart people have thought about this issue at great length and have devised an effective mechanism for doing just that.

Using Sequence Diagrams

There is a perfect, low-cost way to experiment with objects and messages: Sequence Diagrams. Sequence Diagrams are defined in the Unified Modeling Language (UML) and are one of many diagrams that UML supports. Figure 4.2 shows a sampling of some diagrams.

Figure 4.2 A sample of UML diagrams

If you have joyfully embraced UML you already know the value of Sequence Diagrams. If you are unfamiliar with UML and find the previous graphic alarming, fear not. This book is not turning into a UML guide. Lightweight, agile design does not require the creation and maintenance of piles of artifacts. However, the creators of UML put a great deal of thought into how to communicate object oriented design and you can leverage off their efforts. There are UML diagrams that provide excellent, transient ways to explore and communicate design possibilities. Use them; you do not need to reinvent this wheel.

Sequence Diagrams, in particular, are quite handy. They provide a simple way to experiment with different object arrangements and message passing schemes. They bring clarity to your thoughts and provide a vehicle to collaborate and communicate with others. Think of them as a light-weight way to acquire an intention about an interaction. Draw them on a whiteboard, alter them as needed and erase them when they've served their purpose.

Figure 4.3 shows a simple sequence diagram. This diagram represents an attempt to implement the use case above. It shows Moe, a Customer and the Trip class, where Moe sends the suitable_trips message to Trip and gets back a response.

Figure 4.3 A simple sequence diagram

Figure 4.3 illustrates the two main parts of a sequence diagram. As you can see, they show two things: objects and the messages passing between them. The following paragraphs describe the parts of this diagram but please note that the UML police will not arrest you if you vary from the official style. Do what works for you.

In the example diagram each object is represented by two identically named boxes, arranged one above the other and connected by a single vertical line. It contains two objects, the Customer Moe and the class Trip. Messages are shown as horizontal lines. When a message is sent, the line is labeled with the message name. Message lines end or begin with an arrow; this arrow points to the receiver. When an object is busy processing a received message, it is 'active' and its vertical line is expanded to a vertical rectangle.

The diagram also contains a single message, suitable_trips, sent by Moe to the Tripclass. Therefore, this sequence diagram can be read as follows: Customer Moe sends the suitable_trips message to the Trip class, which is activated to process it and then, when finished, returns a response.

This sequence diagram is very nearly an exact, literal translation of the use case. The nouns in the use case became objects in the sequence diagram and the action of the use case turned into a message. The message requires three parameters: on_date, of_difficulty, and need_bike.

While this example serves quite adequately to illustrate the parts of a sequence diagram, the design that it implies should give you pause. In this sequence diagram Moe expects the Tripclass to find him a suitable trip. It seems reasonable that Trip would be responsible for finding trips on a date and of a difficulty, but Moe may also need a bicycle and he clearly expectsTrip to handle that too.

Drawing this sequence diagram exposes the message passing between the Customer Moe and the Trip class and prompts you to ask the question, 'Should Trip be responsible for figuring out if an appropriate bicycle is available for each suitable trip?', or more generally, 'Should this receiver be responsible for responding to this message?'.

Therein lies the value of sequence diagrams. They explicitly specify the messages that pass between objects, and since objects should only communicate using public interfaces, sequence diagrams are a vehicle for exposing, experimenting with and ultimately defining those interfaces.

Also, notice that now that you have drawn a sequence diagram, this design conversation has been inverted. The previous design emphasis was on classes and who and what they knew. Suddenly, the conversation has changed; it is now revolving around messages. Instead of deciding on a class and then figuring out its responsibilities, you are now deciding on a message and figuring out where to send it.

This transition from class based design to message based design is a turning point in your design career. The message based perspective yields more flexible applications than does the class based perspective. Changing the fundamental design question from 'I know I need this class, what should it do?' to 'I need to send this message, who should respond to it?' is the first step in that direction.

You don't send messages because you have objects, you have objects because you send messages.

From a message passing point of view, it is perfectly reasonable for a Customer to send the suitable_trips message. The problem isn't that Customer should not send it, the problem is that Trip should not receive it.

Now that you have the suitable_trips message in mind but no place to send it, you must construct some alternatives. Sequence diagrams make it easy to explore the possibilities.

If the Trip class should not be figuring out if bicycles are available for a trip, perhaps there's a Bicycle class which should. Trip can be responsible for suitable_trips and Bicyclefor suitable_bicycle. Moe can get the answer he needs if he talks to both of them. That sequence diagram looks like figure 4.4.

Figure 4.4 Moe talks to both Trip and Bicycle

Now that you've drawn these two diagrams, consider, for each, what Moe has to know. In the first case, figure 4.3, he knows that:

  • He wants a list of trips.
  • There's an object that implements the suitable_trips message.

In the second case, figure 4.4, he knows that:

  • He wants a list of trips.
  • There's an object that implements the suitable_trips message.
  • Part of finding a suitable trip means finding a suitable bicycle.
  • There's another object that implements the suitable_bicycle message.

Sadly, figure 4.4 is an improvement in some areas but a failure in others. This design removes extraneous responsibilities from Trip but unfortunately merely transfers them to Customer.

The problem in figure 4.4 is that Moe not only knows what he wants, but he also knows how other objects should collaborate to provide it. The Customer class has become the owner of the application rules that assess trip suitability.

When Moe knows how to decide if a trip is suitable, he isn't ordering behavior off of a menu, he's going into the kitchen and cooking. The Customer class is co-opting responsibilities that belong somewhere else and binding itself to a implementation that might change.

Asking for 'What' Instead of Telling 'How'

The distinction between a message that asks for what the sender wants and a message that tells the receiver how to behave may seem subtle but the consequences are significant. Understanding this difference is a key part of creating reusable classes with well defined public interfaces.

To illustrate the importance of what vs how, it's time for a more detailed example. Put the customer/trip design problem aside for a bit; it will return in a few pages. Switch your attention to a new example involving trips, bicycles and mechanics.

In figure 4.5, a trip is about to depart and it needs to make sure that all the bicycles scheduled to be used on it are in good shape. The use case for this requirement is: A trip, in order to start, needs to ensure that all its bicycles are mechanically sound. Trip could know exactly how to make a bike ready for a trip and could ask a Mechanic to do each of those things:

Figure 4.5 A Trip tells a Mechanic how to prepare each Bicycle

In figure 4.5:

  • The public interface for Trip includes the method bicycles.
  • The public interface for Mechanic includes methods clean_bicycle, pump_tires,lube_chain and check_brakes.
  • Trip expects to be holding onto an object that can respond to clean_bicycle, pump_tires, lube_chain and check_brakes.

In this design, Trip knows many details about what Mechanic does. Since Trip contains this knowledge and uses it to direct Mechanic, Trip must change if Mechanic adds new procedures to the bike preparation process. For example, if Mechanic implements a method to check the bike repair kit as part of Trip preparation, Trip must change to invoke this new method.

Figure 4.6 depicts an alternative where Trip asks Mechanic to prepare each Bicycle, leaving the implementation details to Mechanic.

Figure 4.6 A Trip asks a Mechanic to prepare each Bicycle

In figure 4.6:

  • The public interface for Trip includes the method bicycles.
  • The public interface for Mechanic includes method prepare_bicycle.
  • Trip expects to be holding onto an object that can respond to prepare_bicycle.

Trip has now relinquished a great deal of responsibility to Mechanic. Trip knows that it wants each of its bicycles to be prepared and it trusts the Mechanic to accomplish this task. Since the responsibility for knowing how has been ceded to Mechanic, Trip will always get the correct behavior regardless of future improvements to Mechanic.

When the conversation between Trip and Mechanic switched from a how to a what, one side effect was that the size of the public interface in Mechanic was drastically reduced. In figure 4.5 Mechanic exposes many methods, in figure 4.6 its public interface consists of a single method, prepare_bicycle. Since Mechanic promises that its public interface is stable and unchanging, having a small public interface means that there are few methods for others to depend upon. This reduces the likelihood of Mechanic someday changing its public interface, breaking its promise and forcing changes on many other classes.

This change of message patterns is a great improvement to the maintainability of the code but Trip still knows a lot about Mechanic. The code would be more flexible and more maintainable if Trip could accomplish its goals while knowing even less.

Seeking Context Independence

The things that Trip knows about other objects make up its context. Think of it this way: Triphas a single responsibility but it expects a context. In figure 4.6 Trip expects to be holding onto a Mechanic object that can respond to the prepare_bicycle message.

Context is a coat that Trip wears everywhere; any use of Trip, be it for testing or otherwise, requires that its context be established. Preparing a trip always requires preparing bicycles and in doing so Trip always sends the prepare_bicycle message to its Mechanic. You cannot reuse Trip unless you provide a Mechanic-like object that can respond to this message.

The context that an object expects has a direct effect on how difficult it is to reuse. Objects that have a simple context are easy to use and easy to test; they expect few things from their surroundings. Objects that have a complicated context are hard to use and hard to test; they require complicated setup before they can do anything.

The best possible situation is for an object to be completely independent of its context. An object that could collaborate with others without knowing who they were or what they did could be reused in novel and unanticipated ways.

You already know the technique for collaborating with others without knowing who they are: Dependency Injection. The new problem here is for Trip to invoke the correct behavior from Mechanic without knowing what Mechanic does. Trip wants to collaborate with Mechanic while maintaining context independence.

At first glance this seems impossible. Trips have bicycles, bicycles must be prepared and mechanics prepare bicycles. Having Trip ask Mechanic to prepare a Bicycle seems inevitable.

However, it is not. The solution to this problem lies in the distinction between what and how and arriving at a solution requires concentrating on what Trip wants.

What Trip wants is to be prepared. The knowledge that it must be prepared is completely and legitimately within the realm of Trip's responsibilities. However, the fact that bicycles need to be prepared may belong to the provence of Mechanic. The need for bicycle preparation is more how a Trip gets prepared than what a Trip wants.

Figure 4.7 illustrates a third alternative sequence diagram for Trip preparation. In this example, Trip merely tells Mechanic what it wants, i.e., to be prepared, and passes itself along as an argument.

Figure 4.7 A Trip asks a Mechanic to prepare the Trip

In this sequence diagram Trip knows nothing about Mechanic but still manages to collaborate with it to get bicycles ready. Trip tells Mechanic what it wants, passes self along as an argument and Mechanic immediately calls back to Trip to get the list of the Bicyclesthat need preparing.

In figure 4.7:

  • The public interface for Trip includes bicycles.
  • The public interface for Mechanic includes prepare_trip and perhaps prepare_bicycle.
  • Trip expects to be holding onto an object that can respond to prepare_trip.
  • Mechanic expects the argument passed along with prepare_trip to respond to bicycles.

All of the knowledge about how mechanics prepare trips is now isolated inside of Mechanic and the context of Trip has been reduced. Both of the objects are now easier to change, test and reuse.

Trusting Other Objects

The designs illustrated by figures 4.5 through 4.7 represent a movement towards increasingly object oriented code and as such they mirror the stages of development of the novice designer.

Figure 4.5 is quite procedural. A Trip tells a Mechanic how to prepare a Bicycle, almost as if Trip were the main program and Mechanic a bunch of callable functions. In this design Trip is the only object that knows exactly how to prepare a bike; getting a bike prepared requires using a Trip or duplicating the code. Trip's context is large, as is Mechanic's public interface. These two classes are not islands with bridges between them, they are instead a single, woven cloth.

Many new object oriented programmers start out working just this way, writing procedural code. It's inevitable; this style closely mirrors the best practices of their former procedural languages. Unfortunately, coding in a procedural style defeats the purpose of object orientation. It re-introduces the exact maintenance issues that OOP is designed to avoid.

Figure 4.6 is more object oriented. Here, a Trip asks a Mechanic to prepare a Bicycle. Trip's context is reduced, Mechanic's public interface is smaller. Additionally, Mechanic's public interface is now something that any object may profitably use; you don't need a Trip in order to prepare a bike. These objects now communicate in a few well-defined ways; they are less coupled and more easily reusable.

This style of coding places the responsibilities in the correct objects, a great improvement, but continues to require that Trip have more context than is necessary. Trip still knows that it holds onto an object that can respond to prepare_bicycle and it must always have this object.

Figure 4.7 is far more object oriented. In this example Trip doesn't know or care that it has a Mechanic and it doesn't have any idea what the Mechanic will do. Trip merely holds onto an object to which it will send prepare_trip; it trusts the receiver of this message to behave appropriately.

Expanding upon this idea, Trip could place a number of such objects into an array and send each the prepare_trip message, trusting every preparer to do whatever it does because of the kind of thing that it is. Depending on how Trip was being used, it might have many preparers or it might have few. This pattern allows you to add newly introduced preparers to Trip without changing any of its code i.e., you can extend Trip without modifying it.

If objects were human and could describe their own relationships, in figure 4.5 Trip would be telling Mechanic, 'I know what I want and I know how you do it', in figure 4.6, 'I know what I want and I know what you do', and in figure 4.7, 'I know what I want and I trust you to do your part'.

This blind trust is a keystone of object oriented design. It allows objects to collaborate without binding themselves to context and is necessary in any application that expects to grow and change.

Using Messages to Discover Objects

Armed with knowledge about the distinction between what and how and the importance of context and trust, it's time to return to the original design problem from figures 4.3 and 4.4.

Remember that the use case for that problem stated: A customer, in order to choose a trip, would like to see a list of available trips of appropriate difficulty, on a specific date, where rental bicycles are available.

Figure 4.3 was a literal translation of this use case, one in which Trip had too much responsibility. Figure 4.4 was an attempt to move the responsibility for finding available bicycles from Trip to Bicycle but in doing so it placed an obligation on Customer to know far too much about what makes a trip 'suitable'.

Neither of these designs is very reusable or tolerant of change. These problems are revealed, inescapably, in the sequence diagrams. Both designs contain a violation of the single responsibility principle. In figure 4.3, Trip knows too much. In 4.4, Customer knows too much, tells other objects how to behave and requires too much context.

It is completely reasonable that Customer would send the suitable_trips message. That message repeats in both sequence diagrams because it feels innately correct. It is exactly what Customer wants. The problem is not with the sender, it is with the receiver. You have not yet identified an object whose responsibility it is to implement this method.

This application needs an object to embody the rules at the intersection of Customer, Tripand Bicycle. The suitable_trips method will be part of its public interface.

The realization that you need an as yet undefined object is one that you can arrive at via many routes. The advantage of discovering this missing object via sequence diagrams is that the cost of being wrong is very low and the impediments to changing your mind are extremely few. The sequence diagrams are experimental and will be discarded; your lack of attachment to them is a feature. They do not reflect your ultimate design, instead they create an intention which is the starting point for your design.

Regardless of how you reach this point it is now clear that you need a new object, one which you discovered because of your need to send it a message.

Perhaps the application should contain a TripFinder class. Figure 4.8 shows a sequence diagram where a TripFinder is responsible for finding suitable trips.

Figure 4.8 Moe asks the TripFinder for a suitable trip

TripFinder contains all knowledge of what makes a trip suitable. It knows the rules; its job is to do whatever is necessary to respond to this message. It provides a consistent public interface while hiding messy and changeable internal implementation details.

Moving this method into TripFinder makes the behavior available to any other object. In the unknown future perhaps other touring companies will use TripFinder to locate suitable trips via a web service. Now that this behavior has been extracted from Customer, it can be used, in isolation, by any other object.

Creating a Message Based Application

This section used sequence diagrams to explore design, define public interfaces and discover objects.

Sequence diagrams are powerfully useful in a transient way; they make otherwise impossibly convoluted conversations comprehensible. Flip back through the last several pages and imagine attempting this discussion without them.

Useful as they are, they are a tool, nothing more. They help keep the focus on messages and allow you to form a rational intention about the first thing to assert in a test. Switching your attention from objects to messages allows you to concentrate on designing an application built upon public interfaces.

  • + Share This
  • 🔖 Save To Your Account