Home      Discussion      Topics      Dictionary      Almanac
Signup       Login
Mixin

Mixin

Discussion
Ask a question about 'Mixin'
Start a new discussion about 'Mixin'
Answer questions from other users
Full Discussion Forum
 
Encyclopedia
In object-oriented programming language
Object-oriented programming language
This is a list of object-oriented programming programming languages.-Languages with object-oriented features:*ABAP*Ada 95*AmigaE*BETA*Blue*Boo*C++*C#*COBOL*Cobra*ColdFusion*Common Lisp*COOL*CorbaScript*Clarion*CLU*Curl*D*Dylan*E*Eiffel...

s, a mixin is a class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

 that provides a certain functionality to be inherited or just reused by a subclass, while not meant for instantiation (the generation of objects of that class), Mixins are synonymous functionally with abstract base classes
Abstract type
In programming languages, an abstract type is a type in a nominative type system which cannot be instantiated. An abstract type may have no implementation, or an incomplete implementation...

. Inheriting from a mixin is not a form of specialization but is rather a means of collecting functionality. A class may inherit most or all of its functionality from one or more mixins through multiple inheritance
Multiple inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in which a class can inherit behaviors and features from more than one superclass....

.

Mixins first appeared in the Symbolics
Symbolics
Symbolics refers to two companies: now-defunct computer manufacturer Symbolics, Inc., and a privately held company that acquired the assets of the former company and continues to sell and maintain the Open Genera Lisp system and the Macsyma computer algebra system.The symbolics.com domain was...

' object-oriented Flavors system (developed by Howard Cannon), which was an approach to object-orientation used in Lisp Machine Lisp
Lisp Machine Lisp
Lisp Machine Lisp is a dialect of the Lisp programming language, a direct descendant of Maclisp, and was initially developed in the mid to late 1970s as the systems programming language for the MIT Lisp machines. Lisp Machine Lisp was also the Lisp dialect with the most influence on the design of...

. The name was inspired by Steve's Ice Cream Parlor
Steve's Ice Cream
Steve's Ice Cream was an ice-cream parlor chain which attracted media attention and long lines when owner Steve Herrell opened his first establishment at 191 Elm Street in Somerville, Massachusetts in 1973. It introduced the concept of super-premium ice cream and customized ice cream desserts using...

 in Somerville, Massachusetts: The ice cream shop owner 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
Mix-in
A mix-in is a term used to describe a dessert made of ice cream and another flavoring such as candy. Mix-in desserts are traditionally sold in an ice cream parlor and are made at the time of ordering...

", his own trademarked term at the time.

Mixins encourage code reuse
Code reuse
Code reuse, also called software reuse, is the use of existing software, or software knowledge, to build new software.-Overview:Ad hoc code reuse has been practiced from the earliest days of programming. Programmers have always reused sections of code, templates, functions, and procedures...

 and avoid well-known pathologies associated with multiple inheritance. However, mixins introduce their own set of compromises.

A mixin can also be viewed as an interface with implemented methods
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

. When a class includes a mixin, the class implements the interface and includes, rather than inherits, all the mixin's attributes (fields, properties) and methods. They become part of the class during compilation. Mixins don't need to implement an interface. The advantage of implementing an interface is that instances of the class may be passed as parameters to methods requiring that interface.

A mixin can defer definition and binding of methods until runtime, though attributes and instantiation parameters are still defined at compile time
Compile time
In computer science, compile time refers to either the operations performed by a compiler , programming language requirements that must be met by source code for it to be successfully compiled , or properties of the program that can be reasoned about at compile time.The operations performed at...

. This differs from the most widely-used approach, which originated in the programming language Simula
Simula
Simula is a name for two programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard...

, of defining all attributes, methods and initialization at compile time.

Definition and implementation


In Simula
Simula
Simula is a name for two programming languages, Simula I and Simula 67, developed in the 1960s at the Norwegian Computing Center in Oslo, by Ole-Johan Dahl and Kristen Nygaard...

, 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.

With mixins the class definition defines only the attributes and parameters associated with that class; methods are left to be defined elsewhere, as in Flavors and CLOS
CLOS
The Common Lisp Object System is the facility for object-oriented programming which is part of ANSI Common Lisp. CLOS is a powerful dynamic object system which differs radically from the OOP facilities found in more static languages such as C++ or Java. CLOS was inspired by earlier Lisp object...

, and are organized in "generic function
Generic function
In certain systems for object-oriented programming such as the Common Lisp Object System and Dylan, a generic function is an entity made up of all methods having the same name. Typically a generic function itself is an instance of a class that inherits both from function and standard-object...

s". These generic functions are functions which are defined in multiple cases (methods) by type dispatch and method combinations.

CLOS and Flavors allows 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 results of all applicable methods of a generic function are added to compute the return value. This is used for example with the border-mixin for graphical objects. A graphical object may have a width generic function. The border-mixin would add a border around an object and has a method computing its width. A new class bordered-button which 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.

Programming languages that use mixins


Other than Flavors and CLOS (a part of Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

), some languages that use mixins are:
  • Ada
    Ada (programming language)
    Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages...

     (by extending an existing tagged record with arbitrary operations in a generic)
  • Ceylon
    Ceylon Project
    The Ceylon Project is an upcoming programming language and SDK, created by Red Hat. It is based on the Java programming language and when it is released, will run under the Java Virtual Machine....

  • C# (with open source library re-mix )
  • ColdFusion
    ColdFusion
    In computing, ColdFusion is the name of a commercial rapid application development platform invented by Jeremy and JJ Allaire in 1995. ColdFusion was originally designed to make it easier to connect simple HTML pages to a database, by version 2 it had...

     (Class based using includes and Object based by assigning methods from one object to another at runtime)
  • Curl(with Curl RTE)
  • D
    D (programming language)
    The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

     (called "template mixins")
  • Factor
    Factor programming language
    Factor is a stack-oriented programming language created by Slava Pestov. Factor is dynamically typed and has automatic memory management, as well as powerful metaprogramming features. The language has a single implementation featuring a self-hosted optimizing compiler and an interactive development...

  • Fantom
  • Groovy
  • Ioke
    Ioke (programming language)
    Ioke is a dynamic, strongly typed, prototype-based programming language targeting the Java Virtual Machine and the Common Language Runtime. It was designed by Ola Bini, a developer of JRuby. It has a very simple homoiconic syntax, somewhat similar to Io....

  • JavaFX Script
    JavaFX Script
    JavaFX Script is a scripting language designed by Sun Microsystems, forming part of the JavaFX family of technologies on the Java Platform.JavaFX targets the Rich Internet Application domain , specializing in rapid development of visually rich applications for the desktop and mobile markets...

  • JavaScript
    JavaScript
    JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

  • Object REXX
    Object REXX
    The Object REXX programming language is an object-oriented scripting language initially produced by IBM for OS/2. It is a follow-on to and a significant extension of the "Classic Rexx" language originally created for the CMS component of VM/SP and later ported to MVS, OS/2 and PC DOS.On October 12,...

  • OpenLaszlo
    OpenLaszlo
    OpenLaszlo is an open source platform for the development and delivery of rich Internet applications. It is released under the Open Source Initiative-certified Common Public License ....

  • Perl
    Perl
    Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

  • Perl 6
    Perl 6
    Perl 6 is a major revision to the Perl programming language. It is still in development, as a specification from which several interpreter and compiler implementations are being written. It is introducing elements of many modern and historical languages. Perl 6 is intended to have many...

  • PHP
    PHP
    PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

    's "traits"
  • Racket (mixins documentation)
  • Python
    Python (programming language)
    Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

  • Ruby
    Ruby (programming language)
    Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

  • Scala
  • Smalltalk
    Smalltalk
    Smalltalk is an object-oriented, dynamically typed, reflective programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." It was designed and created in part for educational use, more so for constructionist...

  • Strongtalk
    Strongtalk
    Strongtalk is a Smalltalk environment with optional static typing support. Strongtalk can make some compile time checks, and offer "stronger" type-safety guarantees; this is the source of its name...

  • Vala
    Vala (programming language)
    Vala is a programming language created with the goal of bringing modern language features to C, with no added runtime needs and with little overhead, by targeting the GObject object system. It is being developed by Jürg Billeter and Raffaele Sandrini. The syntax borrows heavily from C#...

  • Visual Dataflex
    Visual DataFlex
    Visual DataFlex is a 4GL windows programming language by Data Access, targeted at creating database and client-server type programs.- Architecture :Visual DataFlex has a 3-layer architecture:Bottom layer: At this level you have the database tables....

  • XOTcl
    XOTcl
    XOTcl is an object-oriented extension for the Tool Command Language created by Gustaf Neumann and Uwe Zdun. It is an extension of the MIT OTcl. XOTcl supports metaclasses. Class and method definitions are completely dynamic...

    /TclOO (object systems for Tcl
    Tcl
    Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration", according to the author, with programmers devising their own languages intended to be embedded into applications, Tcl gained acceptance on its own...

    )
  • Self


Some languages like ECMAScript
ECMAScript
ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.- History :JavaScript...

 (commonly referred to as JavaScript) 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. Note that this is also possible with statically typed languages, but it requires constructing a new object with the extended set of methods.

Example


Common Lisp
Common Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...

 provides Mixins in CLOS (Common Lisp Object System) similar to Flavors.

object-width is a generic function with one argument and is using the + method combination. The + method 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. No superclasses. 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 the 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


In the Curl web-content language, multiple inheritance is used as classes with no instances may implement methods. Common mixins include all skinnable ControlUIs inheriting from SkinnableControlUI, user interface delegate objects that require dropdown menus inheriting from StandardBaseDropdownUI and such explicitly named mixin classes as FontGraphicMixin, FontVisualMixin and NumericAxisMixin-of class. Version 7.0 added library access so that mixins do not need to be in the same package or be public abstract. Curl constructors are factories which facilitates using multiple-inheritance without explicit declaration of either interfaces or mixins.

In Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, the SocketServer module has both a UDPServer and TCPServer class that act as a server for UDP
User Datagram Protocol
The User Datagram Protocol is one of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol network without requiring...

 and TCP
Transmission Control Protocol
The Transmission Control Protocol is one of the core protocols of the Internet Protocol Suite. TCP is one of the two original components of the suite, complementing the Internet Protocol , and therefore the entire suite is commonly referred to as TCP/IP...

 socket servers.
Normally, all new connections are handled within the same process.
Additionally, there are two mixin classes: ForkingMixIn and ThreadingMixIn.
By extending TCPServer with the ThreadingMixIn like this

class ThreadingTCPServer(ThreadingMixIn, TCPServer):
pass

the ThreadingMixIn class adds functionality to the TCP server such that each new connection creates a new thread
Thread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...

.
Alternatively, using the ForkingMixIn would cause the process to be forked
Fork (operating system)
In computing, when a process forks, it creates a copy of itself. More generally, a fork in a multithreading environment means that a thread of execution is duplicated, creating a child thread from the parent thread....

 for each new connection.
Clearly, the functionality to create a new thread or fork a process is not terribly useful as a stand-alone class.

In this usage example, the mixins provide alternative underlying functionality without affecting the functionality as a socket server.

Commentary


Some of the functionality of mixins is provided by interfaces in popular languages like Java and C#. However, an interface only specifies what the class must support and cannot provide an implementation. Another class, providing an implementation and dependent with the interface, is needed for refactoring common behavior into a single place.

Interfaces combined with aspect-oriented programming
Aspect-oriented programming
In computing, aspect-oriented programming is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns...

 can produce full fledged mixins in languages that support such features, such as C# or Java. Additionally, through the use of the marker interface pattern
Marker interface pattern
The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects...

, generic programming
Generic programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...

, and extension methods, C# 3.0 has the ability to mimic mixins.

External links

  • MixIn at Portland Pattern Repository
  • Mixins in ActionScript
    ActionScript
    ActionScript is an object-oriented language originally developed by Macromedia Inc. . It is a dialect of ECMAScript , and is used primarily for the development of websites and software targeting the Adobe Flash Player platform, used on Web pages in the form of...

    .
  • Scala Overview: Mixin Class Composition - a step-by-step example in Scala
    Scala programming language
    Scala is a multi-paradigm programming language designed to integrate features of object-oriented programming and functional programming. The name Scala is a portmanteau of "scalable" and "language", signifying that it is designed to grow with the demands of its users...

  • The Common Lisp Object System: An Overview by Richard P. Gabriel and Linda DeMichiel provides a good introduction to the motivation for defining classes by means of generic functions.