It’s tempting to think of object-oriented applications as being the sum of their classes. Classes are so very visible; design discussions often revolve around class responsibilities and dependencies. Classes are what you see in your text editor and what you check in to your source code repository.
There is design detail that must be captured at this level but an object-oriented application is more than just classes. It is made up of classes but defined by messages. Classes control what’s in your source code repository; messages reflect the living, animated application.
Design, therefore, must be concerned with the messages that pass between objects. It deals not only with what objects know (their responsibilities) and who they know (their dependencies), but how they talk to one another. The conversation between objects takes place using their interfaces; this chapter explores creating flexible interfaces that allow applications to grow and to change.
Imagine two running applications, as illustrated in Figure 4.1. Each consists of objects and the messages that pass between them.
In the first application, the messages have no apparent pattern. Every object may send any message to any other object. If the messages left visible trails, these trails would eventually draw a woven mat, with each object connected to every other.
In the second application, the messages have a clearly defined pattern. Here the objects communicate in specific and well-defined ways. If these messages left trails, the trails would accumulate to create a set of islands with occasional bridges between them.
Both applications, for better or worse, are characterized by the patterns of their messages.
The objects in the first application are difficult to reuse. Each one exposes too much of itself and knows too much about its neighbors. This excess knowledge results in objects that are finely, explicitly, and disastrously tuned to do only the things that they do right now. No object stands alone; to reuse any you need all, to change one thing you must change everything.
The second application is composed of plug-able, component-like objects. Each reveals as little about itself, and knows as little about others, as possible.
The design issue in the first application is not necessarily a failure of dependency injection or single responsibility. Those techniques, while necessary, are not enough to prevent the construction of an application whose design causes you pain. The roots of this new problem lie not in what each class does but with what it reveals. In the first application each class reveals all. Every method in any class is fair game to be invoked by any other object.
Experience tells you that all the methods in a class are not the same; some are more general or more likely to change than others. The first application takes no notice of this. It allows all methods of any object, regardless of their granularity, to be invoked by others.
In the second application, the message patterns are visibly constrained. This application has some agreement, some bargain, about which messages may pass between its objects. Each object has a clearly defined set of methods that it expects others to use.
These exposed methods comprise the class’s public interface.
The word interface can refer to a number of different concepts. Here the term is used to refer to the kind of interface that is within a class. Classes implement methods, some of those methods are intended to be used by others and these methods make up its public interface.
An alternative kind of interface is one that spans across classes and that is independent of any single class. Used in this sense, the word interface represents a set of messages where the messages themselves define the interface. Many different classes may, as part of their whole, implement the methods that the interface requires. It’s almost as if the interface defines a virtual class; that is, any class that implements the required methods can act like the interface kind of thing.
The remainder of this chapter will address the first kind of interface, that is, methods within a class and how and what to expose to others. Chapter 5, Reducing Costs with Duck Typing, explores the second kind of interface, the one that represents a concept that is broader than a class and is defined by a set of messages.
Imagine a restaurant kitchen. Customers order food off a menu. These orders come into the kitchen through a little window (the one with the bell beside it, “order up!”) and the food eventually comes out. To a naïve imagination it may seem as if the kitchen is filled with magical plates of food that are waiting, pining to be ordered, but in reality the kitchen is full of people, food, and frenzied activity and each order triggers a new construction and assembly process.
The kitchen does many things but does not, thankfully, expose them all to its customers. It has a public interface that customers are expected to use; the menu. Within the kitchen many things happen, many other messages get passed, but these messages are private and thus invisible to customers. Even though they may have ordered it, customers are not welcome to come in and stir the soup.
This distinction between public and private exists because it is the most effective way to do business. If customers directed the cooking, they would have to be re-educated whenever the kitchen ran low on an ingredient and needed to make a substitution. Using a menu avoids this problem by letting each customer ask for what they want without knowing anything about how the kitchen makes it.
Each of your classes is like a kitchen. The class exists to fulfill a single responsibility but implements many methods. These methods vary in scale and granularity and range from broad, general methods that expose the main responsibility of the class to tiny utility methods that are only meant to be used internally. Some of these methods represent the menu for your class and should be public; others deal with internal implementation details and are private.
The methods that make up the public interface of your class comprise the face it presents to the world. They:
• Reveal its primary responsibility
• Are expected to be invoked by others
• Will not change on a whim
• Are safe for others to depend on
• Are thoroughly documented in the tests
All other methods in the class are part of its private interface. They:
• Handle implementation details
• Are not expected to be sent by other objects
• Can change for any reason whatsoever
• Are unsafe for others to depend on
• May not even be referenced in the tests
Chapter 2, Designing Classes with a Single Responsibility, was about creating classes that have a single responsibility—a single purpose. If you think of a class as having a single purpose, then the things it does (its more specific responsibilities) are what allows it to fulfill that purpose. There is a correspondence between the statements you might make about these more specific responsibilities and the classes’ public methods. Indeed, public methods should read like a description of responsibilities. The public interface is a contract that articulates the responsibilities of your class.
Chapter 3, Managing Dependencies, was about dependencies and its take-home message was that a class should depend only on classes that change less often than it does. Now that you are dividing every class into a public part and a private part, this idea of depending on less changeable things also applies to the methods within a class.
The public parts of a class are the stable parts; the private parts are the changeable parts. When you mark methods as public or private you tell users of your class upon which methods they may safely depend. When your classes use the public methods of others, you trust those methods to be stable. When you decide to depend on the private methods of others, you understand that you are relying on something that is inherently unstable and are thus increasing the risk of being affected by a distant and unrelated change.
Finding 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.
Meet FastFeet, Inc., a bicycle touring company. FastFeet offers both road and mountain bike trips. FastFeet runs its business using a paper system. It currently has 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 that reflects 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 they may choose to bring their own. FastFeet has a few bicycles available for customer rental and it also shares 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.
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.
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 that 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 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.
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.
If you have joyfully embraced UML you already know the value of sequence diagrams. If you are unfamiliar with UML and find the 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 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 lightweight 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 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 Trip
class. 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 Trip
class 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 expects Trip
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 because objects should only communicate using public interfaces, sequence diagrams are a vehicle for exposing, experimenting with, and ultimately defining those interfaces.
Also, notice 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 that should. Trip
can be responsible for suitable_trips
and Bicycle
for suitable_bicycle
. Moe can get the answer he needs if he talks to both of them. That sequence diagram looks like Figure 4.4.
For each of these diagrams, consider what Moe has to know.
In Figure 4.3, he knows that:
• He wants a list of trips.
• There’s an object that implements the suitable_trips
message.
In 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, it merely transfers them to Customer
.
The problem in Figure 4.4 is that Moe not only knows what he wants, 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 an implementation that might change.
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 versus how, it’s time for a more detailed example. Put the customer/trip design problem aside for a bit; it will return soon. 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 all the bicycles scheduled to be used 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:
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. Because 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
.
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. Because 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
. Because 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 on. 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.
The things that Trip
knows about other objects make up its context. Think of it this way: Trip
has 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 are or what they do 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 province 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, that is, to be prepared, and passes itself along as an argument.
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 Bicycles
that 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, to test, and to reuse.
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 reintroduces 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, and 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
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 on 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, that is, 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.
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 Figure 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
, Trip
and 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, but instead they create an intention that 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 that 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.
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.
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.
The clarity of your interfaces reveals your design skills and reflects your self-discipline. Because design skills are always improving but never perfected, and because even today’s beautiful design may look ugly in light of tomorrow’s requirement, it is difficult to create perfect interfaces.
This, however, should not deter you from trying. Interfaces evolve and to do so they must first be born. It is more important that a well-defined interface exist than that it be perfect.
Think about interfaces. Create them intentionally. It is your interfaces, more than all of your tests and any of your code, that define your application and determine it’s future.
The following section contains rules-of-thumb for creating interfaces.
Your goal is to write code that works today, that can easily be reused, and that can be adapted for unexpected use in the future. Other people will invoke your methods; it is your obligation to communicate which ones are dependable.
Every time you create a class, declare its interfaces. Methods in the public interface should
• Be explicitly identified as such
• Be more about what than how
• Have names that, insofar as you can anticipate, will not change
• Take a hash as an options parameter
Be just as intentional about the private interface; make it inescapably obvious. Tests, because they serve as documentation, can support this endeavor. Either do not test private methods or, if you must, segregate those tests from the tests of public methods. Do not allow your tests to fool others into unintentionally depending on the changeable, private interface.
Ruby provides three relevant keywords: public
, protected
, and private
. Use of these keywords serves two distinct purposes. First, they indicate which methods are stable and which are unstable. Second, they control how visible a method is to other parts of your application. These two purposes are very different. Conveying information that a method is stable or unstable is one thing; attempting to control how others use it is quite another.
To further complicate matters, Ruby not only provides these keywords but also supplies various mechanisms for circumventing the visibility restrictions that private
and protected
impose. Users of a class can redefine any method to public
regardless of its initial declaration. The private
and protected
keywords are more like flexible barriers than concrete restrictions. Anyone can get by them; it’s simply a matter of expending the effort.
Therefore, any notion that you can prevent method access by using these keywords is an illusion. The keywords don’t deny access, they just make it a bit harder. Using them sends two messages:
• You believe that you have better information today than programmers will have in the future.
• You believe that those future programmers need to be prevented from accidentally using a method that you currently consider unstable.
These beliefs may be correct but the future is a long way off and one can never be certain. The most apparently stable methods may change regularly and the most initially unstable may survive the test of time. If the illusion of control is a comfort, feel free to use the keywords. However, many perfectly competent Ruby programmers omit them and instead use comments or a special method naming convention (Ruby on Rails, for example, adds a leading ‘_’ to private methods) to indicate the public and private parts of interfaces.
These strategies are perfectly acceptable and sometimes even preferable. They supply information about method stability without imposing visibility restrictions. Use of them trusts future programmers to make good choices about which methods to depend upon based on the increased information they have at that time.
Regardless of how you choose to do so, as long as you find some way to convey this information you have fulfilled your obligations to the future.
Do your best to interact with other classes using only their public interfaces. Assume that the authors of those classes were just as intentional as you are now and they are trying desperately, across time and space, to communicate which methods are dependable. The public/private distinctions they made are intended to help you and it’s best to heed them.
If your design forces the use of a private method in another class, first rethink your design. It’s possible that a committed effort will unearth an alternative; you should try very hard to find one.
When you depend on a private interface you increase the risk of being forced to change. When that private interface is part of an external framework that undergoes periodic releases, this dependency is like a time bomb that will go off at the worst possible moment. Inevitably, the person who created the dependency leaves for greener pastures, the external framework gets updated, the private method being depended upon changes, and the application breaks in a way that baffles current maintainers.
A dependency on a private method of an external framework is a form of technical debt. Avoid these dependencies.
Despite your best efforts you may find that you must depend on a private interface. This is a dangerous dependency that should be isolated using the techniques described in Chapter 3. Even if you cannot avoid using a private method, you can prevent the method from being referenced in many places in your application. Depending on a private interface increases risk; keep this risk to a minimum by isolating the dependency.
Construct public interfaces with an eye toward minimizing the context they require from others. Keep the what verses how distinction in mind; create public methods that allow senders to get what they want without knowing how your class implements its behavior.
Conversely, do not succumb to a class that has an ill-defined or absent public interface. When faced with a situation like that of the Mechanic
class in Figure 4.5, do not give up and tell it how to behave by invoking all of it’s methods. Even if the original author did not define a public interface it is not too late to create one for yourself.
Depending on how often you plan to use this new public interface, it can be a new method that you define and place in the Mechanic
class, a new wrapper class that you create and use instead of Mechanic,
or a single wrapping method that you place in your own class. Do what best suits your needs, but create some kind of defined public interface and use it. This reduces your class’s context, making it easier to reuse and simpler to test.
Having read about responsibilities, dependencies, and interfaces you are now equipped to explore the Law of Demeter.
The Law of Demeter (LoD) is a set of coding rules that results in loosely coupled objects. Loose coupling is nearly always a virtue but is just one component of design and must be balanced against competing needs. Some Demeter violations are harmless, but others expose a failure to correctly identify and define public interfaces.
Demeter restricts the set of objects to which a method may send messages; it prohibits routing a message to a third object via a second object of a different type. Demeter is often paraphrased as “only talk to your immediate neighbors” or “use only one dot.” Imagine that Trip’s depart
method contains each of the following lines of code:
customer.bicycle.wheel.tire
customer.bicycle.wheel.rotate
hash.keys.sort.join(', ')
Each line is a message chain containing a number of dots (periods). These chains are colloquially referred to as train wrecks; each method name represents a train car and the dots are the connections between them. These trains are an indication that you might be violating Demeter.
Demeter become a “law” because a human being decided so; don’t be fooled by its grandiose name. As a law it’s more like “floss your teeth every day,” than it is like gravity. You might prefer not to confess to your dentist but occasional violations will not collapse the universe.
Chapter 2 stated that code should be transparent, reasonable, usable and exemplary. Some of the message chains above fail when judged against TRUE:
• If wheel
changes tire
or rotate
, depart
may have to change. Trip
has nothing to do with wheel
yet changes to wheel
might force changes in Trip
. This unnecessarily raises the cost of change; the code is not reasonable.
• Changing tire
or rotate
may break something in depart
. Because Trip
is distant and apparently unrelated, the failure will be completely unexpected. This code is not transparent.
• Trip
cannot be reused unless it has access to a customer
with a bicycle
that has a wheel
and a tire
. It requires a lot of context and is not easily usable.
• This pattern of messages will be replicated by others, producing more code with similar problems. This style of code, unfortunately, breeds itself. It is not exemplary.
The first two message chains are nearly identical, differing only in that one retrieves a distant attribute (tire
) and the other invokes distant behavior (rotate
). Even experienced designers argue about how firmly Demeter applies to message chains that return attributes. It may be cheapest, in your specific case, to reach through intermediate objects to retrieve distant attributes. Balance the likelihood and cost of change against the cost of removing the violation. If, for example, you are printing a report of a set of related objects, the most rational strategy may be to explicitly specify the intermediate objects and to change the report if it becomes necessary. Because the risk incurred by Demeter violations is low for stable attributes, this may be the most cost-efficient strategy.
This tradeoff is permitted as long as you are not changing the value of the attribute you retrieve. If depart
sends customer.bicycle.wheel.tire
with the intent of altering the result, it is not just retrieving an attribute, it is implementing behavior that belongs in Wheel
. In this case, customer.bicycle.wheel.tire
becomes just like customer.bicycle.wheel.rotate
; it’s a chain that reaches across many objects to get to distant behavior. The inherent cost of this coding style is high; this violation should be removed.
The third message chain, hash.keys.sort.join
is perfectly reasonable and, despite the abundance of dots, may not be a Demeter violation at all. Instead of evaluating this phrase by counting the “dots,” evaluate it by checking the types of the intermediate objects.
hash.keys
returns an Enumerable
hash.keys.sort
also returns an Enumerable
hash.keys.sort.join
returns a String
By this logic, there is a slight Demeter violation. However, if you can bring yourself to accept that hash.keys.sort.join
actually returns an Enumerable
of Strings,
all of the intermediate objects have the same type and there is no Demeter violation. If you remove the dots from this line of code, your costs may well go up instead of down.
As you can see, Demeter is more subtle than first appears. Its fixed rules are not an end in themselves; like every design principle, it exists in service of your overall goals. Certain “violations” of Demeter reduce your application’s flexibility and maintainability, while others make perfect sense.
One common way to remove “train wrecks” from code is to use delegation to avoid the “dots.” In object-oriented terms, to delegate a message is to pass it on to another object, often via a wrapper method. The wrapper method encapsulates, or hides, knowledge that would otherwise be embodied in the message chain.
There are a number of ways to accomplish delegation. Ruby contains delegate.rb
and forwardable.rb
and the Ruby on Rails framework includes the delegate
method. Each of these exists to make it easy for an object to automatically intercept a message sent to self and to instead send it somewhere else.
Delegation is tempting as a solution to the Demeter problem because it removes the visible evidence of violations. This technique is sometimes useful, but beware, it can result in code that obeys the letter of the law while ignoring its spirit. Using delegation to hide tight coupling is not the same as decoupling the code.
Demeter is trying to tell you something and it isn’t “use more delegation.”
Message chains like customer.bicycle.wheel.rotate
occur when your design thoughts are unduly influenced by objects you already know. Your familiarity with the public interfaces of known objects may lead you to string together long message chains to get at distant behavior.
Reaching across disparate objects to invoke distant behavior is tantamount to saying, “there’s some behavior way over there that I need right here and I know how to go get it.” The code knows not only what it wants (to rotate) but how to navigate through a bunch of intermediate objects to reach the desired behavior. Just as Trip
, earlier, knew how Mechanic
should prepare a bike and so was tightly coupled to Mechanic
, here the depart
method knows how to navigate through a series of objects to make a wheel rotate and therefore is tightly coupled to your overall object structure.
This coupling causes all kinds of problems. The most obvious is that it raises the risk that Trip
will be forced to change because of an unrelated change somewhere in the message chain. However, there’s another problem here that is even more serious.
When the depart
method knows this chain of objects, it binds itself to a very specific implementation and it cannot be reused in any other context. Customers
must always have Bicycles,
which in turn must have Wheels
that rotate
.
Consider what this message chain would look like if you had started out by deciding what depart
wants from customer
. From a message-based point of view, the answer is obvious:
customer.ride
The ride
method of customer hides implementation details from Trip
and reduces both its context and its dependencies, significantly improving the design. When FastFeet changes and begins leading hiking trips it’s much easier to generalize from customer.ride
to customer.depart
or customer.go
than to disentangle the tentacles of this message chain from your application.
The train wrecks of Demeter violations are clues that there are objects whose public interfaces are lacking. Listening to Demeter means paying attention to your point of view. If you shift to a message-based perspective, the messages you find will become public interfaces in the objects they lead you to discover. However, if you are bound by the shackles of existing domain objects, you’ll end up assembling their existing public interfaces into long message chains and thus will miss the opportunity to find and construct flexible public interfaces.
Object-oriented applications are defined by the messages that pass between objects. This message passing takes place along “public” interfaces; well-defined public interfaces consist of stable methods that expose the responsibilities of their underlying classes and provide maximal benefit at minimal cost.
Focusing on messages reveals objects that might otherwise be overlooked. When messages are trusting and ask for what the sender wants instead of telling the receiver how to behave, objects naturally evolve public interfaces that are flexible and reusable in novel and unexpected ways.
3.133.159.223