Mixins vs composition in scala

后端 未结 2 1533
暗喜
暗喜 2021-01-29 20:49

In java world (more precisely if you have no multiple inheritance/mixins) the rule of thumb is quite simple: \"Favor object composition over class inheritance\".

I\'d

2条回答
  •  青春惊慌失措
    2021-01-29 21:13

    Other differences you haven't mentioned:

    • Trait classes do not have any independent existence:

    (Programming Scala)

    If you find that a particular trait is used most often as a parent of other classes, so that the child classes behave as the parent trait, then consider defining the trait as a class instead, to make this logical relationship more clear.
    (We said behaves as, rather than is a, because the former is the more precise definition of inheritance, based on the Liskov Substitution Principle - see [Martin2003], for example.)

    [Martin2003]: Robert C. Martin, Agile Software Development: Principles, Patterns, and Practices, Prentice-Hall, 2003

    • mixins (trait) have no constructor parameters.

    Hence the advice, still from Programming Scala:

    Avoid concrete fields in traits that can’t be initialized to suitable default values.
    Use abstract fields instead or convert the trait to a class with a constructor.
    Of course, stateless traits don’t have any issues with initialization.

    It’s a general principle of good object-oriented design that an instance should always be in a known valid state, starting from the moment the construction process finishes.

    That last part, regarding the initial state of an object, has often helped decide between class (and class composition) and trait (and mixins) for a given concept.

提交回复
热议问题