AlgoViz

Mixins and traits

medium 50 min

A mixin or trait is a small bundle of methods that you add to classes that have nothing else in common.

Video lesson · Chapter 1 of 5

Use one behaviour in three unrelated objects

0:00 / 4:44

See it run

Who answers a call, who is asked back, and what happens when one link is missing.

Operations

Who answers?

A call walks through the order until a class has the method.

Step 1 of 5

One object, four classes

userEnhancedUser objectnameAshaEnhancedUser1st in the orderhasnothingJsonMixin2nd in the orderhasto_jsonLogMixin3rd in the orderhaslogUser4th in the orderhasgreet

The object holds the data. The classes stand in one fixed order.

Step 1: One object, four classes

class EnhancedUser(JsonMixin, LogMixin, User):    passuser.to_json()user.greet()print(EnhancedUser.__mro__)
Good for
One ability, many classes
Costs
Readers must know the order

Never guess the order. Print it.

In the real world

The same mixins and traits doing real jobs. Pick one and step through it.

Four classes, four selections. No tree can draw this.

Step 1 of 4

User

JsonLogTime
Useryesyesyes
Product
TaxTable
Session

All three abilities.

Step 1: User

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Reading the host's fields

    critical

    Another bundle adds a field, and this one breaks.

    Wrong
    def to_json(self):    return json.dumps(self.__dict__)
    Right
    def to_json(self):    return json.dumps(self.fields())
  • Calling the base by name

    critical

    The layers between are skipped.

    Wrong
    def save(self, k, v):    Store.save(self, k, v)
    Right
    def save(self, k, v):    super().save(k, v)
  • Shared state by accident

    critical

    A list at class level belongs to all objects of all hosts.

    Wrong
    class Audited:    audit = []
    Right
    class Audited:    def __init__(self, **kw):        super().__init__(**kw)        self.audit = []
  • Base class first

    major

    In Python the base answers before the mixin, and the mixin has no effect.

    Wrong
    class Page(View, LoginRequired): ...
    Right
    class Page(LoginRequired, View): ...
  • toJSON that calls stringify on itself

    major

    JSON.stringify calls toJSON: endless recursion.

    Wrong
    toJSON() { return JSON.stringify(this); }
    Right
    toJSON() { return this.fields(); }
  • A bundle with one host

    minor

    The reader jumps to another file for nothing.

    Wrong
    class UserHelperMixin: ...     # only User uses it
    Right
    class User: ...                # the methods live here

Interview tips

  • Say the contract

    • Requires
    • Provides
    • Holds no state
  • Know the order

    • Python: left first
    • Ruby: last include first
    • Scala: right first
    • Print it
  • Settle names openly

    • Override in the class
    • Prefix shared bundles
    • Guard hosts
  • Know when not

    • State: a part
    • Run time: a decorator
    • More than three: split