Skip to content

Instantly share code, notes, and snippets.

@dsdshcym
Created January 18, 2018 09:42
Show Gist options
  • Save dsdshcym/0c72af9b8374be01c9e0244359c39d06 to your computer and use it in GitHub Desktop.
Save dsdshcym/0c72af9b8374be01c9e0244359c39d06 to your computer and use it in GitHub Desktop.
Composition over Inheritance

Composition over Inheritance

  • State “DONE” from “NEXT” [2017-03-28 Tue 09:56]
  • Inheritance is just a way to easily implement Polymorphic behaviour
  • Prefer a combination of composition and interface implementation
  • Three kinds of polymorphism
    Hoc Polymorphism
    Multiple procedures with the same name are defined in an ad hoc manner, and where one is chosen by the language (perhaps the most specific).
    • The least well behaved kind of polymorphism
    Parametric Polymorphism
    The variation is defined by a parameter
    • Composition is a kind of Parametric Polymorphism
    Subtype Polymorphism
    A procedure defined on a given type, can also work on a whole family of “subtypes” of that type.
    • Inheritance is a kind of Subtype Polymorphism
    • Should be governed by LSP
  • The goal of polymorphism is generally code reuse but it is not the only way to achieve that goal.
  • Good OOP applications can be written using only interface inheritance and compositions
    1. Ban behaviour inheritance or design for it
    2. Prefer composition
  • State “DONE” from “NEXT” [2017-07-24 Mon 12:23]
  • What’s wrong with the inheritance?
    • Multiple inheritance can lead to combinatorial explosion
  • Mixins?
    • The behaviour is not obvious
    • Method name conflicts
    • Mixins are good for defining meta behavior of a class
    • Mixins are just a way to implicitly implement multiple inheritance
  • Composition
    • Nothing is Something
    • Pros
      • SRP
      • high cohesion, low coupling
    • Cons
      • Verbose
      • Need to use Factory or Builder to build objects
      • It’s hard to chage to this mindset
        • Go
          • A programming language that doesn’t have inheritance by design but makes it possible
          • Encourage composition
  • Conclusion
    1. Inheritance is extremely overused
    2. Mixins can achieve implicit multi-inheritance, but it increases code complexity
    3. Composition is the most straightforward and clear approach to maintain dependencies between classes

    You have to remember though that object-oriented programming is just a convention that some programmers came up with in order to help other programmers solve their problems. Don’t be a slave to these rules. Choose the solution that fits your situation best.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment