What is Mixin?

Source: Internet
Author: User
Tags oauth openid
When browsing tornado code, the classes in auth are named after Mixin. this word is strange. I checked the information. someone explained that Mixin is mixin, which is similar to multi-inheritance. The auth module implements OpenID and OAuth. Why does it use the Mixin method? What are the application scenarios of Mixin? What is the difference with the concept of "interface? When browsing tornado code, classes in auth are named after Mixin. this word is strange. I checked the information and someone explained that Mixin is a mix in, which is similar to multi-inheritance. The auth module implements OpenID and OAuth. Why does it use the Mixin method? What are the application scenarios of Mixin? What is the difference with the concept of "interface? Reply content: Mixin uses language features (such as the include syntax of Ruby and multiple inheritance of Python) to implement the combination mode more concisely. .

Take the following Java pseudo code as an example to implement a reusable "Taggable" component and apply it to the Post model:

import java.util.List;import java.util.ArrayList;interface Entity {    public int getId();    public int getKind();}interface Taggable {    public void addTag(int tagId);    public List
  
    getTags();}class TaggableImpl implements Taggable {    private Entity target;    public TaggableImpl(Entity target) {        this.target = target;    }    public void addTag(int tagId) {        int id = target.getId();        int kind = target.getKind();        System.out.println("insert into ... values "                + id + ", "                + kind + ", "                + tagId + ")");    }    public ArrayList
   
     getTags() {        // query from database        return new ArrayList
    
     ();    }}class Post implements Entity, Taggable {    public final static int KIND = 1001;    private Taggable taggable;    private int id;    private String title;    public Post(int id, String title) {        this.id = id;        this.title = title;        this.taggable = new TaggableImpl(this);    }    public int getId() {        return id;    }    public int getKind() {        return KIND;    }    public void addTag(int tagId) {        taggable.addTag(tagId);  // delegate    }    public ArrayList
     
       getTags() {        return taggable.getTags();  // delegate    }}
     
    
   
  
Mixin means mixing.

Similar to multi-inheritance (in fact, Mixin can be considered as an application of multi-inheritance in a specific scenario), but the classes mixed with Mixin and Mixin classes are not Is-To add some (optional) features. You can add different functions to the mixed classes as needed.

The traditional "interface" concept does not contain implementations, while Mixin does. In fact, the role of Mixin and many of Java's 「 AbleThe interfaces at the end are similar. The difference is that Mixin provides (default) implementation, and the class implementing the-able interface in Java needs the class itself to implement these mixed functions (the Serializable interface is an exception ). Take a lunch break.

Like many respondents upstairs, we have to talk about multi-inheritance when talking about Mixin, because the emergence of Mixin is to solve the problem of multi-inheritance. what is the problem of multi-inheritance?

The author lists the following three points in the book "The world of sonchunkong's program:

  1. Complicated structure: if it is a single inheritance, what is the parent class of a class, and what is the parent class of the parent class, it is very clear, because there is only a single inheritance relationship, however, for multi-inheritance, a class has multiple parent classes, and these parent classes have their own parent classes, so the relationship between classes is very complicated.
  2. Fuzzy priority: If I have both Class A and Class C inherited the base class, class B inherited the Class A, and Class D inherited both Class B and Class C, therefore, the sequence in which class D inherits the methods of the parent class should be D, B, A, C, D, B, C, A, or other sequence, which is not clear.
  3. Function conflict: because multiple inheritance has multiple parent classes, a conflict occurs when different parent classes have the same method. If both Class B and Class C have the same method, it is not clear which method D inherits because there are two possibilities.
Of course, you can say that some languages solve this problem, but not all languages want to solve it.

Therefore, in order to solve the problem of multi-inheritance by taking advantage of the multi-inheritance, we propose two things: Specification inheritance and implementation inheritance.

In short, type inheritance refers to a collection of method names, while implementation inheritance allows methods in addition to method names.

Java selects type inheritance, which is called interface in Java (but the default method already exists in Java 8). Ruby chooses implementation inheritance, which can also be called Mixin and module in Ruby.

To some extent, inheritance emphasizes I am, while Mixin emphasizes I can. When you implement this interface or include this module, then you can proceed.

So we can talk about duck typing again. If you want to know more, you can take a look at the book "The world of songben's program. This is a superstitious method. if you want to know the benefits, open the py source code, search for mixin, and try not to use superstition to implement a module that was originally used superstition, so you can feel it. To solve the problem of multiple inheritance, Java introducesInterface)Technology,Lisp and Ruby introducedMix-inTechnology.


Taking Ruby as an example, Mix-in effectively reduces the complexity of multi-inheritance (who is your father, who has a high priority, and what is your sister MethodIs inherited from which father ). In Ruby, the unit of Mix-in is Module).

The Mix-in technique limits multiple inheritance according to the following rules:
  1. Inherited but inherited;
  2. The second and more parent classes must be abstract classes of Mix-in.

The Mix-in class is an abstract class with the following features:
  1. Instances cannot be generated separately;
  2. Common classes cannot be inherited.

In accordance with the above principles, classes have a single tree structure that inherits the same hierarchy, while at the same time sharing functions can be realized (the way is to put the shared functions in the Mix-in class, insert the Mix-in class into the tree structure ).

Java interface solution Type inheritance(Which methods are available for classes), Mix-in solves the problem. Implement inheritance(What data structures and algorithms are used in the class.

So much force, the understanding of Mix-in is, Mix-in is just a technique for implementing multi-inheritance.Multi-inheritance restricted. Mixin is not multi-inheritance. mixin is a duck-type sugar, so you don't have to inherit a batch of interfaces before calling interfaces to each other. Mixin does not have a standard of special authority. I have to make a final conclusion: mixin is a syntactic sugar that implements multi-inheritance in disguise without providing standard multi-inheritance. Mixin implementations of different versions are not the same, but the starting point is to simplify the inheritance relationship based on the allowed inheritance interface and inheritance implementation to avoid the pitfalls of multi-inheritance.


I think the C # extension method is actually a kind of mixin, but it is not implemented through dynamic features such as code copy, but it is very strict at the compiler level to help you encapsulate it. For other static languages, it is very difficult to implement mixin by yourself without multi-inheritance. Some dynamic languages support mixin. if not, it is easy to create one by yourself.


Recently, I used javascript to implement a version of mixin mechanism. to support visual editing, I added capabilities similar to component systems to integrate them into 0.5 Fireball-x, the answer will be updated later.


Click "like" on the phone code. You are welcome to discuss more. It means copying a piece of code to another place during compilation. Mixin is a special multi-inheritance, that is, a subset of multi-inheritance.
The advantage of using Mixin is that it enjoys the simplicity of a single inheritance and the commonality of multiple inheritance.

As a Mixin class, the following conditions must be met:
  1. Instance objects cannot be generated separately. they are abstract classes.
  2. Classes other than Mixin cannot be inherited.
Because of the preceding restrictions, the Mixin class is usually used as a function module and is "mixed" when this function is required, and the class relationship is not complicated (for example, parent class from which the method with the same name inherits ).
Java interfaces only provide multi-inheritance of "specifications. The Mixin class also provides multiple inheritance of "specifications" and "implementations", which is easier to use than interfaces.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.