Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

multiple inheritance - Mixins vs. Traits

What is the difference between Mixins and Traits?

According to Wikipedia, Ruby Modules are sort of like traits. How so?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. Mixins may contain state, (traditional) traits don't.
  2. Mixins use "implicit conflict resolution", traits use "explicit conflict resolution"
  3. Mixins depends on linearization, traits are flattened.

Lecture about traits

ad 1. In mixins you can define instance variables. Traits do not allow this. The state must be provided by composing class (=class using the traits)

ad 2. There may be the name conflict. Two mixins (MA and MB) or traits (TA and TB) define method with the same definition foo():void.

Mixin MA {
    foo():void {
        print 'hello'
    }
}

Mixin MB {
    foo():void {
        print 'bye'
    }
}

Trait TA {
    foo():void {
        print 'hello'
    }
}

Trait TB {
    foo():void {
        print 'bye'
    }
}

In mixins the conflicts in composing class C mixins MA, MB are resolved implicitly.

Class C mixins MA, MB {
    bar():void {
        foo();
    }
}

This will call foo():void from MA

On the other hand while using Traits, composing class has to resolve conflicts.

Class C mixins TA, TB {
    bar():void {
        foo();
    }
}

This code will raise conflict (two definitions of foo():void).

ad 3. The semantics of a method does not depend of whether it is defined in a trait or in a class that uses the trait.

In other words, it does not matter wheter the class consists of the Traits or the Traits code is "copy - pasted" into the class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...