Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 45

Trait-Based Composition with Explicit Methods

This lesson is built with resources from youtube.com, blog.evan-brass.net and 1 more site.

Hello! Let's dive into the next level of compositional patterns.

In our last lesson, we built a robust system for applying mixins using subclass factories and a fluent API (mix(Base).with(...)). We noted, however, that this is an "all-or-nothing" approach: when you apply a mixin, the consuming class inherits all of its functionality. This is powerful, but sometimes we need more granular control.

Today, we will address that limitation. Our goal is to build a trait-based composition system with explicit method inclusion. We will explore what traits are and implement two different patterns in JavaScript to achieve this fine-grained control, moving beyond simple mixins to a system where we can define how methods are combined and resolve conflicts explicitly.

From Mixins to Traits

First, what is the conceptual difference between a mixin and a trait?

  • A Mixin is typically a bundle of functionality that is merged into a class's prototype chain. As we've seen, this is often done by creating an intermediate class that holds the new behavior.
  • A Trait is also a collection of methods, but the key difference lies in the composition process. A true trait system provides policies for handling method name conflicts and allows for more deliberate composition, rather than a simple merge.

As the article "This is not an essay about 'Traits in Javascript'" puts it:

A trait is like a mixin, however with a trait, we can not just define new behaviour, but also define ways to extend or override existing behaviour.

Since JavaScript doesn't have a built-in trait system like some other languages (e.g., Rust or Scala), we will build our own using the powerful functional and object-oriented features we already have.


Pattern 1: Traits as Composition Protocols

Our first approach is to think of traits not just as objects with methods, but as a combination of behaviors and the rules for applying them. We'll call these rules composition protocols.

Let's start by exploring this idea with a practical example.

This is not an essay about 'Traits in Javascript'

The article 'This is not an essay about 'Traits in Javascript'' by Reginald Braithwaite provides an excellent walkthrough of this pattern. Let's start by understanding the problem he sets up and his initial solution using subclass factories, which should be familiar from our previous lesson.

Read the sections 'our toy problem' up to the line 'Now we’ll solve the same problem with traits.' Focus on understanding the goal: combining a Todo class with Coloured functionality to create a TimeSensitiveTodo that needs to override methods from both.

The problem is clear: TimeSensitiveTodo needs functionality from Coloured, but it also needs to provide its own version of getColourRGB. A simple mixin might lead to a conflict or require careful ordering. A trait system gives us the tools to manage this explicitly.

Implementing Protocols

Instead of a single mixin function, we'll create a set of functions, each representing a different "protocol" for adding methods.

This is not an essay about 'Traits in Javascript'

Now for the core of the pattern. Let's study how the article implements the Define and Override protocols. These are higher-order functions that give us precise control over composition.

Read the section 'defining lightweight traits'. Pay close attention to the implementation of Define and Override. Note how Define throws an error on conflict, while Override allows replacement and provides access to the original method.

Let's break down these two protocols:

  1. Define(behaviour):

    • It takes an object (behaviour) containing methods.
    • It returns a function that modifies a class (define(clazz)).
    • This function iterates through the methods in behaviour and adds each one to the class's prototype, but only if a method with that name doesn't already exist. If it does, it throws an error.
    • This is the "safe-add" protocol. It's for including new functionality without the risk of accidental overrides.
    function Define (behaviour) {
      const instanceKeys = Reflect.ownKeys(behaviour);
      return function define (clazz) {
        for (let property of instanceKeys) {
          if (!clazz.prototype[property]) {
            Object.defineProperty(clazz.prototype, property, {
              value: behaviour[property],
              writable: true
            });
          } else {
            throw `Illegal attempt to override ${property}, which already exists.`
          }
        }
        // The article doesn't return the class, but it's good practice for chaining.
        return clazz;
      }
    }
    
  2. Override(behaviour):

    • This protocol is for explicitly overriding existing methods.
    • It also returns a function that modifies a class.
    • It iterates through the methods in behaviour and requires that a method with the same name already exists on the class's prototype.
    • Crucially, it replaces the original method with a new function that receives the original method (overriddenMethodFunction) as its first argument. This gives you super-like capability without a formal super call.
    function Override (behaviour) {
      const instanceKeys = Reflect.ownKeys(behaviour);
      return function overrides (clazz) {
        for (let property of instanceKeys) {
          if (!!clazz.prototype[property]) {
            let overriddenMethodFunction = clazz.prototype[property];
            Object.defineProperty(clazz.prototype, property, {
              value: function (...args) {
                // The new method receives the original as the first argument.
                return behaviour[property].call(this, overriddenMethodFunction.bind(this), ...args);
              },
              writable: true
            });
          } else {
            throw `Attempt to override non-existent method ${property}`;
          }
        }
        return clazz;
      }
    }
    

Composing Protocols into a Trait

With these protocols, we can now assemble a complete "trait" by composing them.

This is not an essay about 'Traits in Javascript'

The real power comes from combining these protocols. Let's see how the article composes them into a single, reusable trait.

Read the section 'composing protocols'. The pipeline function is a standard functional composition utility. See how it's used to create SensitizeTodos, a single function that applies both the Coloured and DeadlineSensitive behaviors with the correct protocols.

The SensitizeTodos trait combines the Define protocol (via Coloured) and the Override protocol (via DeadlineSensitive) into a single, declarative operation. We've successfully built a system for explicit method inclusion and conflict resolution.

Test your understanding!

The raganwald article also mentions Append and Prepend protocols. Here is a possible implementation for Append:

function Append (behaviour) {
  const instanceKeys = Reflect.ownKeys(behaviour);
  return function append (clazz) {
    for (let property of instanceKeys) {
      if (!!clazz.prototype[property]) {
        let originalMethod = clazz.prototype[property];
        Object.defineProperty(clazz.prototype, property, {
          value: function (...args) {
            // Run the original method first
            const returnValue = originalMethod.apply(this, args);
            // Then run the appended behavior
            behaviour[property].apply(this, args);
            // Return the original method's value
            return returnValue;
          },
          writable: true
        });
      } else {
        throw `Attempt to append to non-existent method ${property}`;
      }
    }
    return clazz;
  }
}

Your task: Create a Loggable trait for a simple User class.

  1. The User class has a save() method that simulates saving to a database.
  2. The Loggable trait should use the Append protocol to add logging functionality after the save() method completes.
  3. Compose and apply the trait to the User class.
// A simple function composition utility
const pipeline = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);

class User {
  constructor(name) {
    this.name = name;
  }
  save() {
    console.log(`Saving ${this.name} to the database...`);
    return true;
  }
}

// Your code here...
Show answer

First, we define the behavior we want to append and create a protocol-based function for it.

const loggingBehavior = {
  save() {
    console.log(`User ${this.name} was saved at ${new Date().toISOString()}`);
  }
};

// Create the appender function using our Append protocol
const AppendLogging = Append(loggingBehavior);

Next, we create our Loggable trait by using the pipeline. In this simple case, the pipeline just contains our one appender function.

const Loggable = pipeline(AppendLogging);

Finally, we apply the trait to our User class to create a new, enhanced class.

const LoggableUser = Loggable(User);

// Test it
const user = new LoggableUser('Alice');
const result = user.save();

console.log(`Save operation returned: ${result}`);

/*
Expected output:
Saving Alice to the database...
User Alice was saved at <timestamp>
Save operation returned: true
*/

This shows how we can cleanly add "after" hooks to existing methods without modifying the original class, using a composable and explicit protocol.


Pattern 2: Symbol-Based Traits

Another approach to traits in JavaScript focuses on a different core problem: preventing name collisions. Instead of creating complex composition logic, we can use Symbols to guarantee that our trait's methods have unique keys.

This pattern provides a powerful way to define and check for interfaces without the risk of property name clashes.

Built-In and Custom Traits in JavaScript - Evan Brass

Let's explore this alternative pattern. The article 'Built-In and Custom Traits in JavaScript' by Evan Brass introduces a helper class that leverages Symbols to create traits.

Read the section 'The Pattern: Imitate and Extend Well-Known Symbols'. Focus on the Trait class implementation and how it's used to create Sayable and Drivable. Pay attention to the use of [Sayable]() { ... } syntax to implement the trait.

This pattern is elegant. Let's analyze the Trait helper class:

class Trait {
  constructor(description) {
    this.symbol = Symbol(description);
  }
  [Symbol.toPrimitive]() {
    return this.symbol;
  }
  [Symbol.hasInstance](target) {
    return typeof target == 'object' && target !== null && target[this.symbol] !== undefined;
  }
}
  • constructor: Creates a new, unique Symbol. This is the identity of our trait.
  • [Symbol.toPrimitive]: This is a clever trick. When an object is used in a context where a primitive is expected (like a property key [myObj]), this method is called. By returning this.symbol, we can use the Trait instance itself as a computed property name: [Sayable].
  • [Symbol.hasInstance]: This well-known symbol lets us customize the behavior of the instanceof operator. We can now check if an object implements our trait with myCow instanceof Sayable. The check simply verifies if the object has a property with the trait's unique symbol key.

Implementation looks like this:

const Sayable = new Trait("Can be made to say something.");

class Cow {
  // Explicitly implement the Sayable trait using its unique symbol as the key
  [Sayable]() {
    return "Moooo";
  }
}

const myCow = new Cow();

// We can check if it implements the trait
console.log(myCow instanceof Sayable); // true

// We can call the trait's method
console.log(myCow[Sayable]()); // "Moooo"

This pattern provides explicit inclusion in its purest form. A class implements a trait only if it defines a method with the corresponding unique symbol. There is zero chance of an accidental name collision with other methods like toString or a method from another library.


Comparing the Two Approaches

We've now seen two powerful ways to build trait-based systems in JavaScript:

  1. Protocol-Based Traits (Raganwald):

    • Focus: Composition logic and conflict resolution (Define, Override, Append).
    • Mechanism: Higher-order functions that modify a class prototype.
    • Pros: Extremely flexible. Allows for complex interactions with existing methods (e.g., method advice).
    • Cons: More complex to set up. Relies on string-based property names, so collisions are possible if not managed carefully by the protocols.
  2. Symbol-Based Traits (Brass):

    • Focus: Interface definition and collision avoidance.
    • Mechanism: Using unique Symbols as property keys.
    • Pros: Guarantees no name collisions. Provides clean interface checking with instanceof. Very explicit.
    • Cons: Less concerned with how to compose behavior (e.g., overriding). The implementation is left entirely to the consuming class.

These patterns aren't mutually exclusive. You could even combine them, using a Symbol-based trait to define an interface and a protocol-based system to provide a default implementation.


Conclusion

Today we've moved beyond the "all-or-nothing" nature of mixins to the more granular and explicit world of traits. By building these patterns from scratch, you've gained a much deeper understanding of JavaScript's compositional capabilities.

Key Takeaways:

  • Traits offer more control than mixins by providing policies for method composition and conflict resolution.
  • The protocol-based pattern uses higher-order functions (Define, Override) to create composable rules for how behaviors are added to a class.
  • The symbol-based pattern uses unique Symbols as property keys to define collision-free interfaces and enable instanceof checks for trait implementation.
  • Both patterns empower you to write more modular, reusable, and explicit code, moving away from the fragile nature of deep inheritance chains.

Next Up

We have become adept at composing behavior into our classes. In the next lesson, we'll turn our attention to controlling the classes themselves. We will learn how to use new.target to create abstract base classes that cannot be directly instantiated, a crucial pattern for building robust and intentional class hierarchies.