Why avoid subtyping?

前端 未结 8 933
长发绾君心
长发绾君心 2020-12-02 07:55

I have seen many people in the Scala community advise on avoiding subtyping \"like a plague\". What are the various reasons against the use of subtyping? What are the altern

相关标签:
8条回答
  • 2020-12-02 08:27

    Focusing on subtyping, ignoring the issues related to classes, inheritance, OOP, etc.. We have the idea subtyping represents a isa relation between types. For example, types A and B have different operations but if A isa B we then can use any of B's operations on an A.

    OTOH, using another traditional relation, if C hasa B then we can reuse any of B's operations on a C. Usually languages let you write one with a nicer syntax, a.opOnB instead of a.super.opOnB as it would be in the case of composition, c.b.opOnB

    The problem is that in many cases there's more than one way to relate two types. For example Real can be embedded in Complex assuming 0 on the imaginary part, but Complex can be embedded in Real by ignoring the imaginary part, so both can be seen as subtypes of the other and subtyping forces one relation to be viewed as preferred. Also, there are more possible relations (e.g. view Complex as a Real using theta component of polar representation).

    In formal terminology we usually say morphism to such relations between types and there are special kinds of morphisms for relations with different properties (e.g. isomorphism, homomorphism).

    In a language with subtyping usually there's much more sugar on isa relations and given many possible embeddings we tend to see unnecessary friction whenever we're using the unpreferred relation. If we bring inheritance, classes and OOP to the mix the problem becomes much more visible and messy.

    0 讨论(0)
  • 2020-12-02 08:28

    My answer does not answer why it is avoided but tries to give another hint at why it can be avoided.

    Using "type classes" you can add an abstraction over existing types/classes without modifying them. Inheritance is used to express that some classes are specializations of a more abstract class. But with type classes you can take any existing classes and express that they all share a common property, for example they are Comparable. And as long as you are not concerned with them being Comparable you don't even notice it. The classes don't inherit any methods from some abstract Comparable type as long as you don't use them. It's a bit like programming in dynamic languages.

    Further reads:

    http://blog.tmorris.net/the-power-of-type-classes-with-scala-implicit-defs/

    http://debasishg.blogspot.com/2010/07/refactoring-into-scala-type-classes.html

    0 讨论(0)
提交回复
热议问题