Qortora · Search · Indexed page

en.wikipedia.orgFetched 2026-08-17T12:43:38Z

Mixin - Wikipedia

Mixin - Wikipedia Jump to content Main menu Main menu move to sidebar hide Navigation Main page Contents Current events Random article About Wikipedia Contact us Contribute Help Learn to edit Community portal Recent changes Upload file Special pages Search Search Appearance Donat…

Open original source · Full cached text

Mixin - Wikipedia Jump to content Main menu Main menu move to sidebar hide Navigation Main page Contents Current events Random article About Wikipedia Contact us Contribute Help Learn to edit Community portal Recent changes Upload file Special pages Search Search Appearance Donate Create account Log in Personal tools Donate Create account Log in Contents move to sidebar hide (Top) 1 History 2 Definition 3 Advantages 4 Implementations 5 Programming languages that use mixins 6 Examples Toggle Examples subsection 6.1 Common Lisp 6.2 C++ 6.2.1 Mixin with CRTP 6.2.2 Mixin with annotations 6.3 D 6.4 Java 6.5 JavaScript 6.5.1 The Object-Literal and extend Approach 6.5.2 Mixin with using Object.assign() 6.5.3 The pure function and delegation based Flight-Mixin Approach 6.6 Python 6.7 Ruby 6.8 In other languages 7 Interfaces and traits Toggle Interfaces and traits subsection 7.1 Scala 7.2 Rust 7.3 Swift 8 See also 9 References 10 External links Toggle the table of contents Mixin 12 languages العربية Čeština Deutsch Español Français 日本語 한국어 Nederlands Polski Русский Українська 中文 Edit links Article Talk English Read Edit View history Tools Tools move to sidebar hide Actions Read Edit View history General What links here Related changes Upload file Permanent link Page information Cite this page Get shortened URL Switch to legacy parser Print/export Download as PDF Printable version In other projects Wikidata item Appearance move to sidebar hide From Wikipedia, the free encyclopedia Class used for injecting methods This article is about the programming concept. For the ice cream, see Mix-in. For the company, see Mixin Network. In object-oriented programming languages, a mixin (or mix-in)[1][2][3][4] is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depends on the language. Mixins are sometimes described as being "included" rather than "inherited". Mixins encourage code reuse and can be used to avoid the inheritance ambiguity that multiple inheritance can cause[5] (the "diamond problem"), or to work around lack of support for multiple inheritance in a language. A mixin can also be viewed as an interface with implemented methods. This pattern is an example of enforcing the dependency inversion principle. History [edit] Mixins first appeared in Symbolics's object-oriented Flavors system (developed by Howard Cannon), which was an approach to object-orientation used in Lisp Machine Lisp. The name was inspired by Steve's Ice Cream Parlor in Somerville, Massachusetts:[1] The owner of the ice cream shop offered a basic flavor of ice cream (vanilla, chocolate, etc.) and blended in a combination of extra items (nuts, cookies, fudge, etc.) and called the item a "mix-in", his own trademarked term at the time.[2] Definition [edit] Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes.[6] A mixin class acts as the parent class, containing the desired functionality. A subclass can then inherit or simply reuse this functionality, but not as a means of specialization. Typically, the mixin will export the desired functionality to a child class, without creating a rigid, single "is a" relationship. Here lies the important difference between the concepts of mixins and inheritance, in that the child class can still inherit all the features of the parent class, but, the semantics about the child "being a kind of" the parent need not be necessarily applied. Advantages [edit] It provides a mechanism for multiple inheritance by allowing one class to use common functionality from multiple classes, but without the complex semantics of multiple inheritance.[7] Code reusability: Mixins are useful when a programmer wants to share functionality between different classes. Instead of repeating the same code over and over again, the common functionality can simply be grouped into a mixin and then included into each class that requires it.[8] Mixins allow inheritance and use of only the desired features from the parent class, not necessarily all of the features from the parent class.[9] Implementations [edit] In Simula, classes are defined in a block in which attributes, methods and class initialization are all defined together; thus all the methods that can be invoked on a class are defined together, and the definition of the class is complete. In Flavors, a mixin is a class from which another class can inherit slot definitions and methods. The mixin usually does not have direct instances. Since a Flavor can inherit from more than one other Flavor, it can inherit from one or more mixins. Note that the original Flavors did not use generic functions. In New Flavors (a successor of Flavors) and CLOS, methods are organized in "generic functions". These generic functions are functions that are defined in multiple cases (methods) by class dispatch and method combinations. CLOS and Flavors allow mixin methods to add behavior to existing methods: :before and :after daemons, whoppers and wrappers in Flavors. CLOS added :around methods and the ability to call shadowed methods via CALL-NEXT-METHOD. So, for example, a stream-lock-mixin can add locking around existing methods of a stream class. In Flavors one would write a wrapper or a whopper and in CLOS one would use an :around method. Both CLOS and Flavors allow the computed reuse via method combinations. :before, :after and :around methods are a feature of the standard method combination. Other method combinations are provided. An example is the + method combination, where the resulting values of each of the applicable methods of a generic function are arithmetically added to compute the return value. This is used, for example, with the border-mixin for graphical objects. A graphical object may have a generic width function. The border-mixin would add a border around an object and has a method computing its width. A new class bordered-button (that is both a graphical object and uses the border mixin) would compute its width by calling all applicable width methods—via the + method combination. All return values are added and create the combined width of the object. In an OOPSLA 90 paper,[10] Gilad Bracha and William Cook reinterpret different inheritance mechanisms found in Smalltalk, Beta and CLOS as special forms of a mixin inheritance. Programming languages that use mixins [edit] Other than Flavors and CLOS (a part of Common Lisp), some languages that use mixins are: Ada (by extending an existing tagged record with arbitrary operations in a generic) C++ (using abstract classes with CRTP) C# (since C# 8.0, by means of default methods of interfaces)[11] Cobra ColdFusion (Class based using includes and Object based by assigning methods from one object to another at runtime) Curl (with Curl RTE) D (called "template mixins"; D also includes a "mixin" statement that compiles strings as code.) Dart Eiffel (called "non-conforming inheritance"; uses normal classes inherited using the "inherit {NONE}" keyword)[12] Factor[13] Groovy Go (by struct embedding) Java (since Java 8, by means of default methods of interfaces) JavaScript Delegation - Functions as Roles (Traits and Mixins) Kotlin Less Magik MATLAB[14] OCaml[15] ooRexx Perl (through roles in the Moose extension of the Perl 5 object system) PHP's "traits" Python Racket (mixins documentation) Raku Ruby Rust Sass Scala[16] Smalltalk Swift SystemVerilog XOTcl/TclOO (object systems builtin to Tcl)[17] TypeScript (mixins documentation) Vala Some languages do not support mixins on the language level, but can easily mimic them by copying methods from one object to another at runtime, thereby "borrowing" the mixin's methods. This is also possible with statically typed languages, but it requires constructing a new object with the extended set of methods. Other languages that do not support mixins can support them in a round-about way via other language constructs. For example, Visual Basic .NET and C# support the addition of extension methods on interfaces, meaning any class implementing an interface with extension methods defined will have the extension methods available as pseudo-members. Examples [edit] Common Lisp [edit] Common Lisp provides mixins in CLOS (Common Lisp Object System) similar to Flavors. object-width is a generic function with one argument that uses the + method combination. This combination determines that all applicable methods for a generic function will be called and the results will be added. (defgeneric object-width (object) (:method-combination +)) button is a class with one slot for the button text. (defclass button () ((text :initform "click me"))) There is a method for objects of class button that computes the width based on the length of the button text. + is the method qualifier for the method combination of the same name. (defmethod object-width + ((object button)) (* 10 (length (slot-value object 'text)))) A border-mixin class. The naming is just a convention. There are no superclasses, and no slots. (defclass border-mixin () ()) There is a method computing the width of the border. Here it is just 4. (defmethod object-width + ((object border-mixin)) 4) bordered-button is a class inheriting from both border-mixin and button. (defclass bordered-button (border-mixin button) ()) We can now compute the width of a button. Calling object-width computes 80. The result is the result of the single applicable method: the method object-width for the class button. ? (object-width (make-instance 'button)) 80 We can also compute the width of a bordered-button. Calling object-width computes 84. The result is the sum of the results of the two applicable methods: the method object-width for the class button and the method object-width for the class border-mixin. ? (object-width (make-instance 'bordered-button)) 84 C++ [edit] Mixin with CRTP [edit] In C++, the traditional way one can implement mixins is using the curiously recurring template pattern (CRTP). Since C++23, one can use explicit object parameters to avoid CRTP entirely, as long as the mixin adds only non-static member functions. \nconcept HasKey = requires (const Host& x) {\n { x.key() } -> three_way_comparable<bool>;\n};\n\n// CRTP necessary; explicit object parameters only usable\n// on non-static member functions, not free functions or friend operators\ntemplate <HasKey Host>\nclass CompareByKey {\nprotected:\n CompareByKey() = default;\n ~CompareByKey() = default;\npublic:\n // use a deduced type to allow strong_ordering when possible,\n // but keep other orderings if necessary\n [[nodiscard]]\n friend auto operator<=>(const Host& lhs, const Host& rhs) noexcept {\n return lhs.key() <=> rhs.key();\n }\n\n [[nodiscard]]\n friend bool operator==(const Host& lhs, const Host& rhs) noexcept {\n return lhs.key() == rhs.key();\n }\n};\n\nclass Person : public CompareByKey<Person> {\nprivate:\n string name;\n int age;\npublic:\n Person(string name, int age):\n name{std::move(name)}, age{age} {}\n\n [[nodiscard]]\n tuple<const string&, const int&> key() const noexcept {\n return std::tie(name, age);\n }\n};\n"}}'>import std; using std::string; using std::three_way_comparable; using std::tuple; template <typename Host> concept HasKey = requires (const Host& x) { { x.key() } -> three_way_comparable<bool>; }; // CRTP necessary; explicit object parameters only usable // on non-static member functions, not free functions or friend operators template <HasKey Host> class CompareByKey { protected: CompareByKey() = default; ~CompareByKey() = default; public: // use a deduced type to allow strong_ordering when possible, // but keep other orderings if necessary [[nodiscard]] friend auto operator<=>(const Host& lhs, const Host&…