What is a mixin?

Improving code reuse in Dart

The term "mixin" comes from object-oriented programming and is used in several programming languages besides Dart. It originated in the 1980s as a technique for reusing code between classes in languages such as Smalltalk and was later adopted by other languages such as Ruby, Python and Dart.

In Dart, a mixin is a class that provides specific functionality that can be reused in other classes. Unlike a regular class, a mixin cannot be instantiated directly but is used by mixing it with other classes. The idea behind mixins is to allow classes to share code more flexibly and to avoid duplication of code.

An example of using mixins in Dart could be the implementation of a "Flyer" class that defines the functionality required for an object to fly. Instead of creating a separate class for each type of object that can fly (such as planes, birds, helicopters, etc.), we can define a "Flyer" mixin and mix it with the corresponding classes.

For example, here we define an abstract class "Animal" which defines a method "makeSound" to be implemented by the subclasses. Then, we define a mixin "Flyer" that provides the necessary methods for an animal to fly:

abstract class Animal {
  void makeSound();
}

mixin Flyer {
  void takeOff() => print("Taking off");
  void fly() => print("Flying");
  void land() => print("Landing");
}

class Bird extends Animal with Flyer {
  void makeSound() => print("Chirp chirp");
}

class Airplane with Flyer {
  void fly() => print("Flying at 30,000 feet");
}

void main() {
  var bird = Bird();
  bird.takeOff();
  bird.fly();
  bird.land();
  bird.makeSound(); // Output: Chirp chirp

  var plane = Airplane();
  plane.takeOff();
  plane.fly();
  plane.land();
}

In this example, a class "Bird" is defined which extends the abstract class "Animal" and mixes the mixin "Flyer". You also define an "Airplane" class that mixes the "Flyer" mixin. Then, an instance of each class is created and the methods provided by the mixin "Flyer" (takeOff, fly, land) and the makeSound method provided by the abstract class "Animal" is called. As you can see, the same functionality can be reused in different classes by using mixins in Dart.