Sobes.tech
Junior — Middle

Explain the differences between mixins and extensions in object-oriented programming.

sobes.tech AI

Answer from AI

In object-oriented programming, mixins and extensions serve for code reuse but work differently:

  • Mixins are classes or sets of methods that can be "mixed into" another class, adding functionality without inheritance. Usually, mixins are not meant for standalone use but for behavior composition. In languages that support mixins (e.g., Dart), they help avoid issues with multiple inheritance.

  • Extensions are a way to add new methods to existing classes without modifying their source code and without inheritance. Extensions allow "extending" the functionality of classes even if you do not have access to their source code.

Example in Dart:

mixin LoggerMixin {
  void log(String message) {
    print('Log: $message');
  }
}

class MyClass with LoggerMixin {
  void doSomething() {
    log('Doing something');
  }
}

extension NumberParsing on String {
  int toInt() {
    return int.parse(this);
  }
}

void main() {
  var obj = MyClass();
  obj.doSomething(); // Uses mixin

  var number = '123'.toInt(); // Uses extension
  print(number);
}

Thus, mixins add behavior through inheritance, while extensions add methods to existing types.