What is a mixin?
Answer
A mixin is a class or interface that provides reusable functionality that can be "mixed into" other classes without requiring inheritance in the traditional sense. Mixins add behavior without establishing a hierarchical relationship. Problem they solve: in single-inheritance languages, you can't inherit from multiple classes. Mixins allow reusing code across class hierarchies. Java implementation via interfaces with default methods: interface Loggable { default Logger getLogger() { return LoggerFactory.getLogger(getClass()); } default void logInfo(String message) { getLogger().info(message); } default void logError(String message, Throwable t) { getLogger().error(message, t); } } interface Cacheable { Map<String, Object> getCache(); default <T> T getFromCache(String key, Supplier<T> loader) { Map cache = getCache(); if (!cache.containsKey(key)) { cache.put(key, loader.get()); } return (T) cache.get(key); } } class UserService implements Loggable, Cacheable { private Map<String, Object> cache = new HashMap<>(); @Override public Map<String, Object> getCache() { return cache; } public User getUser(int id) { logInfo("Fetching user: " + id); // From Loggable return getFromCache("user:" + id, () -> fetchFromDB(id)); // From Cacheable } }. Ruby mixins (most true form): module Serializable def to_json JSON.generate(instance_variables.map { |var| [var.to_s, instance_variable_get(var)] }.to_h) end end class User include Serializable attr_accessor :name, :email end. Python: multiple inheritance used for mixins. Benefits: code reuse without inheritance hierarchy, compose behaviors independently, avoids diamond problem (if designed carefully).