Sunteți pe pagina 1din 9

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

Articles | News | Weblogs | Buzz | Books | Forums Leading-Edge Java | Discuss | Print | Email | Screen Friendly Version | Previous | Next Sponsored Link

Leading-Edge Java

Design Principles from Design Patterns


A Conversation with Erich Gamma, Part III
by Bill Venners
Ju n e 6 , 2 005

Summary
In this interv iew, Erich Gam m a, co-author of the landm ark book, Design Patterns, talks with Bill Venners about two design principles: program to an interface, not an im plem entation, and fav or object com position ov er class inheritance. Erich Gam m a lept onto the software world stage in 1 9 9 5 as co-author of the best-selling book Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley , 1 9 9 5) [1 ]. This landm ark work, often referred to as the Gang of Four (GoF) book, cataloged 2 3 specific solutions to com m on design problem s. In 1 9 9 8, he team ed up with Kent Beck to produce JUnit [2 ], the de facto unit testing tool in the Jav a com m unity . Gam m a currently is an IBM Distinguished Engineer at IBM's Object Technology International (OTI) lab in Zurich, Switzerland. He prov ides leadership in the Eclipse com m unity , and is responsible for the Jav a dev elopm ent effort for the Eclipse platform [3 ]. On October 2 7 , 2 004 , Bill Venners m et with Erich Gam m a at the OOPSLA conference in Vancouv er, Canada. In this interv iew, which will be published in m ultiple installm ents in Leading-Edge Java on Artim a Dev eloper, Gam m a giv es insights into software design. In Part I: How to Use Design Patterns, Gam m a describes giv es his opinion on the appropriate way s to think about and use design patterns, and describes the difference between patterns libraries, such as GoF, and an Alexandrian pattern language. In Part II: Erich Gam m a on Flexibility and Reuse, Gam m a discusses the im portance of reusability , the risks of speculating, and the problem of fram eworkitis. In this third installm ent, Gam m a discusses two design principles highlighted in the GoF book: program to an interface, not an im plem entation, and fav or object com position ov er class inheritance.
1 de 9 13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

Program to an interface, not an implementation


Bill Venners: In the introduction of the GoF book, y ou m ention two principles of reusable object-oriented design. The first principle is: "Program to an interface, not an im plem entation." What's that really m ean, and why do it? Erich Gamma: This principle is really about dependency relationships which hav e to be carefully m anaged in a large app. It's easy to add a dependency on a class. It's alm ost too easy ; just add an im port statem ent and m odern Jav a dev elopm ent tools like Eclipse ev en write this statem ent for y ou. Interestingly the inv erse isn't that easy and getting rid of an unwanted dependency can be real refactoring work or ev en worse, block y ou from reusing the code in another context. For this reason y ou hav e to dev elop with open ey es when it com es to introducing dependencies. This principle tells us that depending on an interface is often beneficial. Bill Venners: Why ? Erich Gamma:Once y ou depend on interfaces only , y ou're decoupled from the im plem entation. That m eans the im plem entation can v ary , and that's a healthy dependency relationship. For exam ple, for testing purposes y ou can replace a heav y database im plem entation with a lighter-weight m ock im plem entation. Fortunately , with today 's refactoring support y ou no longer hav e to com e up with an interface up front. You can distill an interface from a concrete class once y ou hav e the full insights into a problem . The intended interface is just one 'extract interface' refactoring away . So this approach giv es y ou flexibility , but it also separates the really v aluable part, the design, from the im plem entation, which allows clients to be decoupled from the im plem entation. One question is whether y ou should alway s use a Jav a interfaces for that. An abstract class is good as well. In fact, an abstract class giv es y ou m ore flexibility when it com es to ev olution. You can add new behav ior without breaking clients. Bill Venners: How's that? Erich Gamma: In Jav a when y ou add a new m ethod to an interface, y ou break all y our clients. When y ou hav e an abstract class, y ou can add a new m ethod and prov ide a default im plem entation in it. All the clients will continue to work. As alway s there is a trade-off, an interface giv es y ou freedom with regard to the base class, an abstract class giv es y ou the freedom to add new m ethods later. It isn't alway s possible to define an interface in an abstract class, but in the light of ev olution y ou should consider whether an abstract class is sufficient. Since changing interfaces breaks clients y ou should consider them as im m utable once y ou'v e published them . As a consequence when adding a new m ethod to an interface y ou hav e to do so in a separate interface. In Eclipse we take API stability seriously and for this reason y ou will find so called I*2 interfaces like

2 de 9

13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

IMarkerResolution2 or IWorkbenchPart2 in our APIs. These interfaces add m ethods to the base interfaces IMarkerResolution and IWorkbenchPart. Since the additions

are done in separate extension interfaces y ou do not break the clients. Howev er, there is now som e burden on the caller in that they need to determ ine at run- tim e whether an object im plem ents a particular extension interface. Another lesson learned is that y ou should focus not only on dev eloping v ersion one, but to also think about the following v ersions. This doesn't m ean designing in future extensibility , but just keeping in m ind that y ou hav e to m aintain what y ou produce and try to keep the API stable for a long tim e. You want to build to last. That's been an im portant them e of Eclipse dev elopm ent since we started. We hav e built Eclipse as a platform . We alway s keep in m ind as we design Eclipse that it has to last ten or twenty y ears. This can be scary at tim es. We added support for ev olution in the base platform when we started. One exam ple of this is the IAdaptable interface. Classes im plem enting this interface can be adapted to another interface. This is an exam ple of the Extension Object pattern,. [4 ] Bill Venners: It's funny nowaday s we're so m uch m ore adv anced, but when we say build to last, we m ean ten or twenty y ears. When the ancient Egy ptians built to last, they m eant... Erich Gamma: Thousands of y ears, right? But for Eclipse, ten to twenty y ears, wow. Quiet honestly , I don't env ision a software archeologist finding an Eclipse installation stored som ewhere on a hard disk in ten or twenty y ears. I really m ean that Eclipse should still be able to support an activ e com m unity in ten or twenty y ears.

The value of interfaces


Bill Venners: Abov e y ou said interfaces are m ore v aluable. What is their v alue? Why are they m ore v aluable than the im plem entation? Erich Gamma: An interface distills the collaboration between objects. An interface is free from im plem entation details, and it defines the v ocabulary of the collaboration. Once I understand the interfaces, I understand m ost of the sy stem . Why ? Because once I understand all the interfaces, I should be able to understand the v ocabulary of the problem . Bill Venners: What do y ou m ean by "v ocabulary of the problem ?" Erich Gamma: What are the m ethod nam es? What are the abstractions? The abstractions plus the m ethod nam es define the v ocabulary . The Jav a Collections package is a good exam ple for this. The v ocabulary for how to work with collections is distilled in interfaces like List or Set. There is a rich set of im plem entations for these interfaces, but once y ou understand the key interfaces y ou get them all.

3 de 9

13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

Bill Venners: I guess the core of m y question about "program to an interface, not to an im plem enation," is this: In Jav a, there's a special kind of class called interface that if I'm writing I put in code fontthe Jav a interface construct. But then there's the object-oriented interface concept, and ev ery class has that object-oriented interface concept. If I'm writing client code and need to use an object, that object's class exists in som e ty pe hierarchy . At the top of the hierarchy , it's v ery abstract. At the bottom , it's v ery concrete. The way I think about program m ing to interfaces is that, as I write client code, I want to write against the interface of the ty pe that's as far up that hierarchy as I can go, without going too far. Ev ery single one of those ty pes in the hierarchy has a contract. Erich Gamma: You're right. And, writing against a ty pe far up in the hierarchy is consistent with the program m ing to an interface principle. Bill Venners: How can I write to an im plem entation? Erich Gamma: Im agine I define an interface with fiv e m ethods, and I define an im plem entation class below that im plem ents these fiv e m ethods and adds another ten m ethods. If only the interface is published as API then if y ou call one of these ten m ethods y ou m ake an internal call. You call a m ethod that is out of contract, which I m ight break any tim e. So it's the difference, as Martin Fowler would say , between public and published. Som ething can be public, but that doesn't m ean y ou hav e published it. In Eclipse we hav e the nam ing conv ention that a package which includes the segm ent "internal" identifies internal packages. They contain ty pes which we do not consider published ty pes ev en when the package includes a public ty pe. So the nice short package nam e is for API and the long nam e is for internals. Obv iously using package priv ate classes and interfaces is another w ay to hide im plem entation ty pes in Jav a. Bill Venners: Now I understand what y ou m ean. There's public and published. Martin Fowler has nice term s for that difference. Erich Gamma: And in Eclipse we hav e the conv entions for that difference. Actually we ev en hav e tool support. In Eclipse 3 .1 we hav e added support for defining rules for which packages are published API. These access rules are defined on a project's class path. Once y ou hav e these access restrictions defined the Eclipse Jav a dev elopm ent tools report access to internal classes in the sam e way as any other com piler warnings. For exam ple y ou get feedback as y ou ty pe when y ou add a dependency to a ty pe that isn't published. Bill Venners: So if I write code that talks to the interface of a non-published class, that's a way I am writing to the im plem entation, and it m ay break. Erich Gamma: Yes, and the explanation from the angle of the prov ider is that I

4 de 9

13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

need som e freedom and reserv e the right to change the im plem entation.

When to think about interfaces


Bill Venners: On the subject of interfaces, the GoF book includes som e UML class diagram s. UML diagram s seem to m ix interface and im plem entation. When y ou look at it, y ou often see the design of the code. It isn't necessarily obv ious what's API and what's im plem entation. If y ou look at Jav aDoc, by contrast, y ou see the interfaces. Another place I see the lack of differentiation between interface and im plem entation is XP. XP talks about the code. You're changing this am orphous body of code with testdriv en dev elopm ent. When should the designer think about interfaces v ersus the whole m ass of code? Erich Gamma: You m ight think differently when y ou design an application than when y ou design a platform . When y ou design a platform , y ou hav e to care at ev ery m om ent about what to expose as part of y our API, and what to keep internal. Today 's refactoring support m akes it triv ial to change nam es so y ou hav e to be careful not to change published APIs by accident. This goes bey ond just defining which ty pes are published. You also hav e to answer questions like: do y ou allow clients to subclass from this ty pe? If y ou do, it im poses big obligations. If y ou look at the Eclipse API, we try to m ake it v ery explicit whether we intend that clients subclass from a ty pe. Also with Jim des Riv ires [5] we hav e an API adv ocate in our team . He helps us not only to com ply with our rules but ev en m ore im portantly Jim helps us to tell a consistent story with our APIs. When it com es to applications, ev en there y ou hav e abstractions that hav e m ultiple v ariations. For y our design y ou want to com e up with key abstractions, and then y ou want to hav e y our other code just interact with those abstractions, not with the specific im plem entations. Then y ou hav e flexibility . When a new v ariation of an abstraction com es up, y our code still works. Regarding XP, as I m entioned earlier, the m odern refactoring tools allow y ou to introduce interfaces into existing code easily and therefore is consistent with XP. Bill Venners: So for an application it's the sam e thought process as for a platform , but on a sm aller scale. Another difference is that it is easy for m e if I hav e control of all the clients to this interface I can update them if I need to change the interface. Erich Gamma: Yes, for an application it is the sam e thought process as for a platform . You also want to build an application so that it lasts. Reacting to a changing requirem ent shouldn't ripple through the entire app. The fact that y ou hav e control ov er all the clients helps. Once y ou hav e giv en out y our code and y ou no longer hav e access to all the clients, then y ou're in the API business. Bill Venners: Ev en if those clients are written by a different group in the sam e com pany . Erich Gamma: Ev en there, absolutely .

5 de 9

13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

Bill Venners: So it sounds like thinking about interfaces becom es m ore im portant as the project scales up. If the project is just two or three people, it is not quite as im portant to think about the interfaces, because if y ou need to change them y ou change them . The refactoring support tools... Erich Gamma: ... will do it all for y ou. Bill Venners: But if it is a 1 00-person team , that m eans people will be partitioned into groups. Different groups will hav e different areas of responsibility . Erich Gamma: A practice that we follow is to assign a com ponent to a group. The group is responsible for the com ponent and publishes its API. Dependencies are then defined through API. We also resist the tem ptation to define friend relationships, that is, where som e com ponents are m ore equal than others and are allowed to use internals. In Eclipse all com ponents are equal. For exam ple, the Jav a dev elopm ent tool plug-ins hav e no special priv ileges and use the sam e APIs as all other plug-ins. Once y ou hav e published an API then it is y our responsibility to keep them stable. Otherwise y ou will break the other com ponents and nobody is able to m ake progress. Hav ing stable APIs is a key to m aking progress in a project of this size. In a closed env ironm ent as y ou hav e described it y ou hav e m ore flexibility when it com es to m aking changes. For exam ple, y ou can use the Jav a deprecation support to allow other team s to gradually catch-up with y our changes. In such an env ironm ent y ou can rem ov e deprecated m ethods after som e agreed on tim e-interv al. This m ight not be possible in a fully exposed platform . There deprecated m ethods cannot be rem ov ed since y ou m ay still break a client som ewhere.

Composition versus inheritance


Bill Venners: The other principle of object-oriented design that y ou offer in the GoF introduction is, "Fav or object com position ov er class inheritance." What does that m ean, and why is it a good thing to do? Erich Gamma: I still think it's true ev en after ten y ears. Inheritance is a cool way to change behav ior. But we know that it's brittle, because the subclass can easily m ake assum ptions about the context in which a m ethod it ov errides is getting called. There's a tight coupling between the base class and the subclass, because of the im plicit context in which the subclass code I plug in will be called. Com position has a nicer property . The coupling is reduced by just hav ing som e sm aller things y ou plug into som ething bigger, and the bigger object just calls the sm aller object back. From an API point of v iew defining that a m ethod can be ov erridden is a stronger com m itm ent than defining that a m ethod can be called. In a subclass y ou can m ake assum ptions about the internal state of the superclass when the m ethod y ou ov erride is getting called. When y ou just plug in som e behav ior, then it's sim pler. That's why y ou should fav or com position. A com m on

6 de 9

13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

m isunderstanding is that com position doesn't use inheritance at all. Com position is using inheritance, but ty pically y ou just im plem ent a sm all interface and y ou do not inherit from a big class. The Jav a listener idiom is a good exam ple for com position. With listeners y ou im plem ent a listener interface or inherit from what is called an adapter. You create a listener object and register it with a Button widget, for exam ple. There is no need to subclass Button to react to ev ents. Bill Venners: When I talk about the GoF book in m y design sem inar, I m ention that what shows up ov er and ov er is m ostly using com position with interface inheritance for different reasons. By interface inheritance I m ean, for exam ple, inheriting from pure v irtual base classes in C+ + , or code font interface inheritance in Jav a. The Listener exam ple y ou m ention, for instance, has inheritance going on. I im plem ent MouseListener to m ake MyMouseListener. When I pass an instance to a JPanel v ia addMouseListener, now I'm using com position because the front-end JPanel that's holding onto that MouseListener will call its mouseClicked m ethod. Erich Gamma: Yes, y ou hav e reduced the coupling. In addition y ou now hav e a separate listener object and y ou m ight ev en be able to connect it with other objects. Bill Venners: That extra flexibility of com position ov er inheritance is what I'v e observ ed, and it's som ething I'v e alway s had difficulty explaining. That's what I was hoping y ou could capture in words. Why ? What is really going on? Where does the increased flexibility really com e from ? Erich Gamma: We call this black box reuse. You hav e a container, and y ou plug in som e sm aller objects. These sm aller objects configure the container and custom ize the behav ior of the container. This is possible since the container delegates som e behav ior to the sm aller thing. In the end y ou get custom ization by configuration. This prov ides y ou with both flexibility and reuse opportunities for the sm aller things. That's powerful. Rather than giv ing y ou a lengthy explanation, let m e just point y ou to the Strategy pattern. It is m y prototy pical exam ple for the flexibility of com position ov er inheritance. The increased flexibility com es from the fact that y ou can plug-in different strategy objects and, m oreov ers, that y ou can ev en change the strategy objects dy nam ically at run-tim e. Bill Venners: So if I were to use inheritance... Erich Gamma: You can't do this m ix and m atch of strategy objects. In particular y ou cannot do it dy nam ically at run-tim e.

Next week
Com e back Monday , June 1 3 th for the next installm ent of this conv ersation with Erich Gam m a. If y ou'd like to receiv e a brief weekly em ail announcing new articles at Artim a Dev eloper, please subscribe to the Artim a Newsletter.

7 de 9

13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

Talk back!
Hav e an opinion about the design patterns topics discussed in this article? Discuss this article in the Articles Forum topic, Design Principles from Design Patterns.

Resources
[1 ] Erich Gam m a is co-author of Design Patterns: Elements of Reusable Object-Oriented Software, which is av ailable on Am azon.com at: http://www.am azon.com /exec/obidos/ASIN/02 01 6 3 3 6 1 2 / [2 ] Erich Gam m a is co-creator of JUnit, the defacto standard Jav a unit testing tool: http://www.junit.org/index.htm [3 ] Erich Gam m a leads the Jav a dev elopm ent effort for the Eclipse tool platform : http://www.eclipse.org/ [4 ] See "Extension Object," in Robert Martin, Pattern Languages of Program Design 3. Addison- Wesley , 1 9 9 7 , av ailable on Am azon.com at: http://www.am azon.com /exec/obidos/ASIN/02 01 3 1 01 1 2 / [5] "Ev olv ing Jav a-based APIs," by Jim des Riv ires: http://eclipse.org/eclipse/dev elopm ent/jav a-api-ev olution.htm l [See also] Contributing to Eclipse: Principles, Patterns, and Plug-I ns, by Erich Gam m a and Kent Beck, is av ailable on Am azon.com at: http://www.am azon.com /exec/obidos/ASIN/03 2 1 2 057 58/

About the author


Bill Venners is president of Artim a Software, Inc. and editor-in-chief of Artim a Dev eloper. He is author of the book, I nside the Java Virtual Machine, a program m eroriented surv ey of the Jav a platform 's architecture and internals. His popular colum ns in Jav aWorld m agazine cov ered Jav a internals, object-oriented design, and Jini. Bill has been activ e in the Jini Com m unity since its inception. He led the Jini Com m unity 's Serv iceUI project, whose Serv iceUI API becam e the de facto standard way to associate user interfaces to Jini serv ices. Bill also serv es as an elected m em ber of the Jini Com m unity 's initial Technical Ov ersight Com m ittee (TOC), and in this role helped to define the gov ernance process for the com m unity .
Leading-Edge Java | Discu ss | Print | Email | Screen Friendl y V ersion | Previou s | N ext

Copyright 1996-2009 Artima, Inc . All Rights Reserved. - Privac y Polic y - T erms of Use - Advertise with Us

8 de 9

13-01-2011 21:28

Design Principles from Design Patterns

http://www.artima.com/lejava/articles/designprincip...

9 de 9

13-01-2011 21:28

S-ar putea să vă placă și