DEV Community

Cover image for Mixins in Dart: A Better Way to Share Code
Belli
Belli

Posted on

Mixins in Dart: A Better Way to Share Code

The official (and confusing) documentation of mixins in Dart does not highlight — at least not for me — the usefulness of this amazing property. Programming is literally having the knowledge of a new language and as developers, our job is to understand the language we're "speaking." The deeper our understanding, the more valuable our solutions can be.

Mixins allow software to make use of an important concept from the SOLID principles: the OOpen/Closed Principle.
This principle states that software entities such as classes, modules, and functions should be open for extension but closed for modification. In other words, you should be able to add new functionality to your code without changing existing, stable code.

The bigger the project, the more important it is to follow this principle. Consider a scenario where multiple devs are working on a feature at the same time, or even more critical, when the project lacks test coverage to guarantee existing functionalities. Modifying a class, even if it doesn’t break the code immediately, will eventually cause problems at some edge case (If you haven’t been there yet, don’t worry, you will).

All this introduction to explain a “simple” concept: class extension without hierarchies.

A mixin in Dart is a way to reuse a class’s code in multiple class hierarchies. Mixins let you add methods and properties to classes without using inheritance.

Key differences:

  • A normal class can be instantiated (you can create objects from it), while a mixin cannot.
  • A mixin is used to add functionality to other classes, not to create objects.
  • You use the with keyword to apply a mixin to a class.

Let’s see an example of usage in code:

mixin Logger {
  void log(String message) => print('Log: $message');
}

class MyClass with Logger {}

void main() {
  MyClass().log('Hello'); // prints: Log: Hello
}
Enter fullscreen mode Exit fullscreen mode

In Summary

Use mixins to share code and add new behaviors to classes without creating a rigid inheritance hierarchy. They're a flexible and powerful tool for adhering to the Open/Closed Principle and keeping your codebase clean and modular.

Top comments (0)