Composition versus Inheritance

One score (minus five) years ago, in the age of yore and of our programming forefathers, there was written a little book. A seminal book. A book that would change things. That book was called Design Patterns: Elements of Reusable Object-Oriented Software

There were many other greater and some lesser (but still great) works that were released around the same time (1995), but this one has remained a popular favorite among the object-oriented development crowd for some time.  Recently (as in the last 4-5 years) this book has seen a resurgence of popularity due to the increasing use of and references to various design patterns contained in the book.  These “recipes” help us to build software and our object systems designs more consistently and thoughtfully. Sure, patterns can be abused and can be used by less knowledgeable people to stamp out bad software just as bad as if they didn’t have them, but for the knowledgeable, they are a powerful tool.

But this post isn’t about design patterns. No, it’s about the arguably more important portions of this book which deal with fundamentals of object systems design. These principles, upon which those design patterns are based, are more important to learn. These principles are at least partially enumerated in the book’s first chapter. Yet, seemingly, they appear to be all but lost today – at least in the .NET programming crowd.  I have seen elements of this in the Java space, I know they still do it this way in C++. Ruby and Python are a little different in this regard, but their user bases are also not immune to a lack of OO principles like all the other OO languages to one degree or another.  I’m talking specifically about the over-use (or indeed abuse) of inheritance when composition is clearly superior for object designs.

As I have grown in my understanding of design and architecture, I have come to realize that the first chapter — titled “Introduction” — of this book is actually the most valuable part of it. I think the entire crowd of us OO brethren and sistren should read it again and absorb it if we can.  If you already own this book, I suggest you re-read chapter 1 again.  If you don’t own it, borrow it from a friend (likely you know someone who owns it – just ask), check it out from the library, or go buy a copy.  If you’re really short on time or don’t like reading heavy architecture books, then at least just read starting at Section 1.6 near the bottom of page 17 (heading: Programming to an Interface, not an Implementation) and continuing through to page 20, stopping (if you want) before the heading Delegation.

In this post, I’d like to go through a few of the important points in this short, but powerful portion of the book to drive them home.

Programming to an Interface, Not an Implementation

This one was a little more difficult to pull off in C++ due to its peculiar way of typing objects. It didn’t have the concept of “interface” as we know it today in C# and Java (though you could achieve this type of functionality). I have a strong suspicion that this is where C# and Java users’ preoccupation with inheritance comes from.

In the book, the author says:

[Manipulating objects solely in terms of their interface and not their implementation] so greatly reduces implementation dependencies between subsystems that it leads to the following principle of reusable object-oriented design:

Program to an interface, not an implementation.

Don’t declare variables to be instances of particular concrete classes. Instead, commit only to an interface defined by an abstract class.

This point is profound and if it isn’t already something you religiously practice, I suggest you do some more research on this topic. Coupling between types directly is the hardest, most pernicious form of coupling you can have and thus will cause considerable pain later.

Consider this code example:

public string GetLastUsername()
  return new UserReportingService().GetLastUser().Name;

As you can see, our class is directly new()’ing up a UserReportingService.  If UserReportingService changes, even slightly, so must our class. Changes become more difficult now and have wider-sweeping ramifications. We have now just made our design more brittle and therefore, costly to change. Our future selves will regret this decision.  Put plainly, the “new” keyword (when used against non-framework/core-library types) is potentially one of the most dangerous and costly keywords in the entire language – almost as bad as “goto” (or “on error resume next” for the VB/VBScript veterans out there). 

What, then, can a good developer do to avoid this? Extract an interface from UserReportingService (-> IUserReportingService) and couple to that. But we still have the problem that if my class can’t reference UserReportingService directly, where will the reference to IUserReportingService come from? Who will create it? And once its created, how will my object receive it? This last question is the basis for the Dependency Inversion principle. Typically, dependencies are injected through your class’ constructor or via setter methods (or properties in C#).

Creational Patterns Considered Obsolete

The very next paragraph in the book addresses the issue of who will create the UserReportingService by mentioning the “Creational” patterns. Consider this quote from the book:

You have to instantiate concrete classes (that is, specify a particular implementation) somewhere in your system, of course, and the creational patterns let you do just that.  By abstracting the process of object creation, these patterns give you different ways to associate an interface with its implementation transparently at instantiation.  Creational patterns ensure that your system is written in terms of interfaces, not implementations.

It’s also the case that the act of creating (new()’ing) an object is actually a responsibility in and of itself. A responsibility that your object, which is focused on getting the username of the last user who accessed the system, should not be doing. This concept is known as the Single Responsibility Principle (also see this article).  It’s a subtle distinction, and we usually don’t think of the “new” keyword as a responsibility until you consider the ramifications of that simple keyword.  What if UserReportingService itself has dependencies that need satisfied?  Your class would have to satisfy them.  What if there are special conditions that need to be met in order for UserReportingService to be instantiated properly (existing connection to the database/open transaction, access to the file system, etc). The direct use of UserReportingService could substantially impact the functioning of your class and therefore must be carefully used and designed.  To restate, in order to use another class like UserReportingService, your class must be fully responsible and aware of the impacts of using that class.

The Creational patterns are concerned with removing that responsibility and concern from your class and moving it to another class or system that is designed for and prepared to handle the complex dependencies and requirements of the classes in your system.  This notion is very good and has served us well over the last 15 years. However, the Abstract Factory and Builder pattern implementations, to name two, became increasingly complicated and convoluted. Many started reaching the conclusion that, in a well-designed and interface-based object architecture, dealing with the creation and dependency chain management of all these types/classes/objects (for there will be many more in an interface-based architecture and that is OK), a tool was needed.  People experimented with generating code for their factories and such, but that turned out not to be flexible enough.

Inversion of Control Containers

To combat the increasing complexity and burden of managing factories, builders, etc, the Inversion of Control Container was invented.  It is, in a sense, an intelligent and flexible amalgamation of all the creational patterns. It is an Abstract Factory, a Builder, has Factory Methods, is a (usually) and can manage Singleton instances, and provides Prototype capabilities. It turns out that even in small systems, you need all of these patterns in some measure or another.  As people turned more and more of their designs over to interface-dependencies, dependency inversion and injection, and inversion of control, they rediscovered a new power that was there all along, but not as easy to pull off: composition.

By centralizing and managing your dependency graph as a first class part of your system, you can more easily implement all the other patterns such as Chain of Responsibility, Decorator, etc. In fact, you could implement many of these patterns with little to no code. Objects that had inverted their control over their dependencies could now benefit from that dependency graph being managed and composited via an external entity: the IoC container.

Composition Realized

As the use of IoC Containers (also just known as ‘containers’) grew wider and deeper, new patterns of use emerged and a new world of flexibility in architecture and design was opened up.  Composition which, before containers, was reserved for special occasions could now be used more often and to fuller effect. Indeed, in some circumstances, the container could implement the pattern for you!

Why is this important? Because composition is important. Composition is preferable to inheritance and should be your first route of reuse, NOT inheritance. I repeat, NOT inheritance. Many, certainly in the .NET space, will go straight for inheritance. This eventually leads to a dark place of many template methods (abstract/virtual methods on the base class) and large hierarchies of base classes (only made worse in a language that allows for multiple inheritance). A common example of template method abuse are methods named “OnBefore” or “OnAfter.” 

Don’t just take my word for it, let’s go back to the Design Patterns book (with inline comments and emphasis added by me):

[Inheritance] can cause problems when you’re trying to reuse a subclass.  Should any aspect of the inherited implementation not be appropriate for new problem domains, the parent class must be rewritten or replaced by something more appropriate.  This dependency limits flexibility and ultimately reusability.

Object composition is defined dynamically at run-time (at startup, config-time in most IoC containers –Chad) through objects acquiring references to other objects.  Composition requires objects to respect each others’ interfaces, which in turn requires carefully designed interfaces that don’t stop you from using one object with many others.  But there is a payoff.  Because objects are accessed solely through their interfaces, we don’t break encapsulation.  Any object can be replaced at run-time by another as long as it has the same type.  Moreover, because an object’s implementation will be written in terms of object interfaces, there are substantially fewer implementation dependencies (!!! Very important –Chad)

Object composition has another effect on system design.  Favoring object composition over class inheritance helps you keep each class encapsulated and focused on one task.  Your classes and class hierarchies will remain small and will be less likely to grow into unmanageable monsters.  On the other hand, a design based on object composition will have more objects (if fewer classes), and the system’s behavior will depend on their interrelationships instead of being defined in one class (configured and managed by the IoC container –Chad).

Anyone who has maintained a large system with more than a few objects should hopefully appreciate these sentiments. It is highly likely you’ve had large (as in lines of code) classes, complicated base class inheritance chains, many abstract or virtual methods (template methods) and a tangled web of interconnected dependencies. Even if you had implemented any of the creational patterns, you still should’ve experienced significant pain (whether you felt it or not) any time a more-than-minor change came along. The friction and pain would grow with time and as the complexity of the application grew leading, invariably, to “The Great Rewrite.” Either that, or you left the project and the next team rewrote it because they immediately felt the pain you may have grown accustomed to.

For many of us, this led to seeking out a better way and thus a sort of “rediscovery” of what was lost: The relevant wisdom contained in the first chapter of the Design Patterns book that most of us just skipped past or didn’t comprehend the first time around.

This leads me to the the most important point of this whole blog post and the culmination of everything I’ve been learning, saying, and teaching in the past 2 years (quoting from the book):

That leads us to our second principle of object-oriented design:

Favor object composition over class inheritance

Are You Thinking Compositionally?

So if you’re still with me, and you’re buying what I’m selling here (composition over inheritance), then you’re likely thinking: What can I be doing (more)?  Strive to think more compositionally. Make more, smaller classes. Use interfaces to separate the dependencies of classes. Limit how many dependencies classes take. Push more and more of the work of assembling your object dependency graph into your Container. Don’t have a container? Get a good one!

Once you’re heavily using a container, you can start to do more and fancier things with it. You can begin layering behavior instead of modifying existing behavior (thinking compositionally makes the Open Closed principle easy to pull off and, in fact, natural).

If you’re still not getting it, ask yourself this:  Would adding a new major area of functionality to your application involve changing any base classes?  Would changing your existing functionality to work differently (say adding layers of caching, or exposing services as JSON or WCF services) involve making lots of changes to existing classes? If you needed to layer on error handling or logging, could you do it without touching any existing code?  With composition, you can do all these things easily by simply configuring it through your container.

Final Thoughts

Composition is not something you add on to an existing inheritance-based designed — without significant re-engineering effort that is. You can add some composition, but to make it fully compositional involves a different way of thinking and a fundamentally different architecture. Going from composition to inheritance is easy because it’s a degradation. Going from inheritance to composition is difficult and significant because it’s major improvement and fundamentally different concept.

Therefore, if you find yourself on the cusp of starting a new design, framework, API, product, or whatever it is you’re going to do: Please consider starting from a compositional approach and sparingly adding a little inheritance where it makes sense and doesn’t compromise the larger design.

In conclusion, I don’t think I can say it any better than the “Gang of Four” did in the Design Patterns book, so I’ll leave you with their last thoughts on composition over inheritance:

Ideally you shouldn’t have to create new components to achieve reuse.  You should be able to get all the functionality you need just by assembling existing components through object composition (via the container –Chad). But this is rarely the case, because the set of available components is never quite rich enough in practice.  Reuse by inheritance makes it easier to make new components that can be composed with old ones. Inheritance and object composition thus work together (preferably with composition being the primary mode, inheritance being the finer-grained mode of change -Chad).

Nevertheless, our experience is that designers overuse inheritance as a reuse technique and designs are often made more reusable (and simpler) by depending more on object composition. You’ll see object composition applied again and again in the design patterns.

About Chad Myers

Chad Myers is the Director of Development for Dovetail Software, in Austin, TX, where he leads a premiere software team building complex enterprise software products. Chad is a .NET software developer specializing in enterprise software designs and architectures. He has over 12 years of software development experience and a proven track record of Agile, test-driven project leadership using both Microsoft and open source tools. He is a community leader who speaks at the Austin .NET User's Group, the ADNUG Code Camp, and participates in various development communities and open source projects.
This entry was posted in Advice, composition, Principles. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Well stated, Chad. I continue to find myself amazed at the number of devs who fail or willfully ignore the ease of development that can follow the adoption of an IoC container. Then again, their use of IoC containers would probably scare most people off. And of course, the biggest argument against is always “simplicity.” I found this presentation to explain why that idea is ridiculous: I hope you enjoy it. :)

    • Marko Marko

      Chad. I continue to find myself amazed at the number of devs who fail
      or willfully ignore the ease of development that can follow the adoption
      of an IoC container. Then again, their use of IoC containers would
      probably scare most people off. And of course, the biggest argument
      against is always “simplicity.” I found this presentation to explain why
      that idea is ridiculous:   easycap driver

  • BTW, what are your thoughts on using delegates as a means of removing the barriers to composition? After all, a Func achieves the same end goal while removing the dependencies almost completely. You now depend upon a type but not instances of any objects, at least not directly. I’m finding this immensely powerful in my latest projects. (Of course I’m using DI at the higher levels; you can only go so far.)

  • Scott Sparkman

    Nicely put. Coming from a C++ background where inheritance was heavily used, I’ve seen first hand the dependency problems this creates.

    The hardest thing for me to quantify is the single responsibility principle. I get it when people say that a class changes for one reason and one reason only, but what exactly does that mean. Doesn’t this lead to anemic domain classes? Is this a bad thing?

  • @Ryan: Jeremy recently added this to StructureMap (or will be soon) based on a feature in AutoFac. You can have a Func injected into your c’tor so you can do late binding for stuff that’s volatile and you don’t use in the c’tor, but later when some method on the class it used.

    We had problems sometimes with ISession or IRepository being injected and created by something when it wasn’t necessarily going to be used until later (when a transaction was initiated or some stuff).

    So yeah, I’m all for it for specific scenarios. I’m not sure how I feel about it for wide-spread common use yet. I’ll have to see how it plays out with our usage and on the StructureMap mailing list.

    @Scott: Your domain should change for domain purposes (adding or removing functionality to/from a domain object). You should have to change your “User” object, for example, if you want to support Windows authentication vs. Forms authentication in your Web application.

    Anemic domain is bad, yes. But SRP doesn’t mean you have to have anemic domain, though!

  • jdn

    Good stuff, Chad. Glad to see you blogging again, hope it continues.

  • MM

    great post. it’s funny how once these ideas “click” in your head they seem stupidly obvious and you start to get frustrated by how much code is not written this way.

  • Yes yes yes! I agree! Posted about the evils on inheritance here:

    Composition is much better, now we just need a construct to default delegation to a base implementation.

  • Thanks for the great post. I’d like to ask about using composition without Interfaces and/or IoC. It happens that I build small/medium solutions and I found that I noramally tend to use composition & dependency injection most of the time even before I know that I do. I tried before to use IoC & I felt It was over-engineered design. I understand the value of IoC but I don’t know why I couldn’t make it work for me. Is it because I work on small businesses or I’m missing something vital about them?
    Same applies for Interfaces, some designs doesn’t have interfaces at all & some had interfaces in a meaningful usage, from my point of view, and sometimes I felt that Interfaces are not introducing anything new to the solution just I wanted to have interfaces around. Event removing them later won’t hurt the solution. Forgive me If it’s too stupid quesitons I’m a humble developer working hard to enhance my skills :)

  • @Waheed:

    I use StructureMap on any project involving more than 2-3 classes, it seems. I may write a little command-line utility that’s all procedural. And then I need to add to it, and add to it. Eventually I switch from hacking on it to treating it like a real project and move things into objects, etc. As soon as I do that, I use interfaces to manage dependencies and when I do that, an IoC tool makes sense.

    I’m not sure how you to interface coupling, dependency inversion and injection without an IoC tool. You must have to write factories and do a lot of manual setup and dependency resolution yourself? This is what an IoC tool is.

    It sounds like you haven’t gotten used to using a tool. I had the same problem at first. I cut my teeth on Spring.NET but found it inadequate and almost gave up. Eventually Jeremy Miller sat me down and walked me through StructureMap and some basic usage and WOW my eyes were opened. It was like a whole new world.

    Are you going to be anywhere near in Austin, TX any time soon? I can sit down with you if you are. Otherwise, do you know any colleagues near by your home that could help you? You really owe it to yourself to try to learn StructureMap because it really will help you tremendously.

    Another point: One reason I do some of the (seemingly) extra work of interfaces and IoC is to facilitate my testing. If you’re not unit testing, then I can see how all these things (interfaces, DI, IoC) can seem like a lot of extra work. All these things build upon themselves to deliver a lot of value. An automobile is a lot more complicated than a bike, but an automobile is much more effective — if you’re willing to put up with the extra complexity and hassle. This is similar to interface-based design, dependency inversion and injection, IoC tooling, etc.

  • Rogério

    I am sorry, but you have misunderstood the intended meaning of “Program to an interface, not an implementation”.

    This principle does not tell you to avoid coding to the implicit public interface of a concrete class. It tells you to code to the separate interface the class implements, IF it implements one already. The idea wasn’t to encourage developers to go out of their way creating pointless abstractions in the form of separated interfaces or abstract classes, but to encourage them to use available abstractions. For example, don’t declare a variable/field/parameter/return type as being ArrayList if you only need a List. That’s it.

    Therefore, there is nothing inherently wrong with code like “new UserReportingService().GetLastUser().Name”. If the UserReportingService class would not benefit from implementing a separate interface (probably because there would never exist a second implementation), then it shouldn’t. Simple as that.

    Note also that the statement “if UserReportingService changes, even slightly, so must our class” is utter non-sense.
    Changing the internal implementation of a class will not require changes to the client, if the contract isn’t violated.

  • @seagile
  • @Rogerio:

    I’m sorry, but you’re wrong. It is absolutely talking about creating abstractions to class, and not just dealing with return types (although those things go hand in hand).

    And “so must our class [change]” is not non-sense. What if you add a new parameter to the constructor?

    You are too easily dismissive of these things. I suspect you haven’t spent much time outside of inheritance.

  • @Rogerio: One other thing, whether there is a second implementation or not is not the point. Although there often is: Unit tests.

    There are many reasons for creating abstractions using interfaces (that you so easily dismiss as ‘pointless’). Using composition by abstracting coupling gives you lots of flexibility — a flexibility I use often in my code.

  • Rogério, the intended meaning of the statement: “Program to an interface, not an implementation” was to advise *against* programming to concrete types, not merely to prefer an existing explicit interface if one happens to be available. To help understand this better, I would second Chad’s recommendation to read (or re-read) this section of the Design Patterns book.

    Concerning the UserReportingService example, given Chad’s statement was made within the context of discussing the creation of the object, I don’t think he meant to imply that any slight change to the concrete UserReportingService would be an issue, but changes concerning the object’s creation.

    There are actually several issues with directly instantiating the UserReportingService type. First, if the requirements for creating the UserReportingService change, all clients would be affected. Second, if any client needed to use a different implementation, it would need to be modified. Third, any breaking changes within this service would be reflected in the tests for all clients (i.e. unit testing would not be possible for the consuming clients).

    Hope this helps.

  • Ant

    Great article – good recap of relevant points. I cant help but think how the industry seems to be moving towards a composition style of architecture in general with recent popularity of SOA and OSGI – pluggable/orchestrated style of design that, on purpose or not, thrives off of composition on a macro level.

  • Thanks, that was valuable. Unluckily, I’m no way close to Austin, TX. I’ll use your reply as a guideline for the second trial.

    I think right I do the startup job manually I create objects & inject them to proper classes and they do by their turn inject them to who depends on them & so on through layers.
    I do unit testing, but not for all projects & sure I don’t think it’s mature-enough skill but I’m working on.

    Your comment completes my understanding for an issue I faced two weeks ago. While, building an integration solution based on TIBCO EMS .NET Client.
    I faced a difficulity to isolate or mock the Connection or ConnectionFactory objects from my code in order to test an issue without hitting the connection.
    At the end, I gave up & felt bad because of lake of interfaces. Am I, sort of, Right? :)

  • @Waheed:

    Breaking tight coupling is especially important when dealing with 3rd party components which aren’t designed well (like ADO.NET, and I’m sure your TIBCO library is probably this way also).

    The point of abstracting these things is not to answer the question, “What if we ever want to change our TIBCO implementation?”, it’s to answer the question: “How can I test my code in relation to TIBCO?” and also the question, “How can I easily modify my code to add and change features without having to deal with the complications of TIBCO’s dependencies?”

  • Tom

    Digital Media Minute pointer of the day. Nice to see foundational stuff argued with passion, in the comments as well.

  • @Waheed:

    Or really, it’s mostly “can I write *my* code without having to wrestle with Tibco at the same time?” You most definitely want to be able to exercise your core code before you get Tibco involved.

  • Jason

    Concerning the statement:

    “If you needed to layer on error handling or logging, could you do it without touching any existing code?”

    Can you give a container agnostic example of how to do this? For example given the following interface:

    public interface IService {
    void DoStuff();

    And the concrete implementation:

    public class SomeService: IService {

    public override void DoStuff() {
    …. some stuff;

    How would I add logging to the SomeService DoStuff method without changing the class to depend on some instance of ILogger (through constructor or property injection) or some other logging interface?

    P.S. Sorry for the formatting of the pseudo code if it doesn’t show up properly.

  • @Jason:

    In that case, I might create a LoggingService : IService that took the *real* IService in it’s c’tor

    public class LoggingService : IService{
    private IService _realService;
    private ILogger _log;
    public LoggingService(IService realService, ILogger log){
    _realService = realService;
    _log = log;

    public void DoStuff() {
    _log.Log(“Doing some stuff”);

  • Jason


    Thanks for the quick response. That makes since.

    My only other question would be, how would I wire both services up to a container and be sure that I am only returning the new LoggingService when I request an IService instance? I assume I would want to wire the SomeService up to the container so the LoggingService could receive it in it’s constructor.

    Sorry for all the questions, but I’m just trying to improve my craft.

  • @Jason:

    In StructureMap, you’d do something like:


  • @Jason:

    The beauty of doing this through an IoC container is that your options are opened greatly. You could have another service determine which IService to use. For example:

    For().Use(ctx =>
    return ctx.Get().GetService();

    IServiceStrategy could then examine the current runtime environment (for example pulling the current IoC container context, the Http Request, thread-local storage, hit the database, etc and determine which IService to return.

    The possibilities are limitless, really.

    To be sure, you don’t want to go too crazy here, you want to keep your IoC config light and thin and defer decisions and important logic OUT of your container config (into things like strategies or chains of responsibility, etc).

    But the idea is, since your app is no longer responsible for constructing dependencies and it is all configured through the container, you can move things around and change things compositionally through your container without having to change any existing code (except your IoC container configuration)

  • Michael Reuss

    I’m confronted with C++ again and there don’t seem to be that many great containers out there. Currently I try PocoCapsule – Is anyone aware of a more StructureMap like approach in C++?

  • hiro


    Alternatively, you can also use AOP for the logging bit.

  • @hro, jason:

    In my experience, AOP (for logging at least) is usually poor-mans composition. A way of cracking the nut of inheritance-based designs without changing the design. It’s a “bolt-on” or a hack most of the time.

    I have found that by using more compositional designs, I don’t need AOP.

  • Rogério

    A few counter-points:
    1) Changing the signature of a public constructor is the same as changing the signature of a public method: both methods and constructors belong to the public interface of the class. Obviously, changes to the public API will affect existing clients.
    Don’t confuse “interface” with “Separated Interface”.
    2) I prefer composition over inheritance, but base classes (which I create when it makes sense) don’t need to implement a separate interface. The interface of the base class (which may be abstract or not) is already a good enough abstraction.
    3) Unit tests (and I assume that “mocks” or “fakes” were meant) don’t need separate interfaces at all. With Java, it’s very easy to provide mocks or fake implementations for concrete classes, whether they implement a separate Java interface or not.

    But the really important point I want to repeat here is: don’t misinterpret what the GoF book says. Please read pages 17-18 carefully. The GoF authors were talking about *polymorphism* and about *reducing implementation dependencies between subsystems*. They were *not* talking about having all concrete classes implement a separate interface or abstraction. Such a thing would be absurd, and would only lead to over-designed systems with lots of pointless separate interfaces (and I have seen this in the real world, sadly).

  • Frustrated at Rogério

    @Rogério – I disagree and I think *you* have misunderstood. That is all I have to say.

  • Rogério

    To the ones disagreeing with what I said: it’s ok to disagree, but bear in mind this is a technical discussion. If you don’t have any arguments to support your position, why are you even posting here?

    I will give more evidence to support my arguments. First, see this article by one of the GoF authors:

    Note the parts saying “This principle tells us that depending on an interface is *often* beneficial.”, and the other one saying “Fortunately, with today’s refactoring support you no longer have to come up with an interface up front. You can distill an interface from a concrete class once you have the full insights into a problem. The intended interface is just one ‘extract interface’ refactoring away.” And of course, he was talking about *separate* interfaces, not “interface” in the general sense. Again, it’s perfectly fine to create classes which only have implicit interfaces, and this does not violate the principle. The GoF authors never intended to encourage generalized creation of separate interfaces, but only in situations where up-front design is justified to achieve *reusable* code.

  • Rogério

    An excellent article which should clear up things:

  • @Rogério:

    When I read that article, I saw it as supporting my case and refuting yours.

    What Fowler wanted to do was basically extract an interface on Vector, for example, because Vector didn’t have an explicit interface. The Java library was designed incorrectly here and only allowed inheritance, not composition. You could only derive from Vector and change only the virtual things (which is probably most), but you still get some implementation whether you want it or not.

    If the Java library designers had created IVector and created a default Vector, but only ever coupled to the abstraction (IVector), Fowler never would have had problems with this.

    This problem is systemic in the .NET BCL as well.

  • Its important to make people feel comfort near us. We are need other people in our life. We cant live alone in this life. That is why we need to make a good realtion to all the people around us.

  • Ladfur

    I could tell how great you are in your field of interest. You could relate in each detail very well.

  • Xenshun

    Writing Service

    I am going to save the URL and will definitely visit again. Keep it up.

  • _ryan

    I know this is a year old but i felt the need to comment.

    at Rogerio:

    1)  “API” never refers to the public interface of a class, it refers to a well defined interface (that should be immutable) that is distributed for other people to use your class / subsystem.  This interface never, NEVER contains a constructor method, because the interface is not a class.  Hiding the details of object construction is one of the reasons you want to use an interface.  The object would be created through a Factory or Factory method, which should be designed well enough to handle changes to the object constructors. 

    Your peppering of the discussion with mention of the “Separated Interface” enterprise pattern does nothing but add confusion.  The creation of many small, client specific interfaces (even in the same package) is not a bad thing;  it is actually encouraged by the Interface Segregation Principle of class design (google “Uncle Bob SOLID”).   

    2) >>The interface of the base class (which may be abstract or not) is already a good enough abstraction.

    Not if you need to add new functionality for other clients.  That is the whole point of ISP.

    3) >>Unit tests (and I assume that “mocks” or “fakes” were meant) don’t need separate interfaces at all. With Java, it’s very easy….

    You are making a very broad statement, and backing it up with a Java specific example.  Is providing mock implementations (in the absence of an interface) still easy in other languages like C++ / C#?

  • smith biwan

    Loved to read your jay-z tickets I would like to suggest you that traffic show most people read blogs on Mondays. cheap kanye west tickets So it should encourage blogger to write new write ups over the weekend primarily. cheap adele tickets