Decorating with Traits
You can use traits to decorate objects with capabilities—see the Decorator pattern in Gamma et al.’s Design Patterns: Elements of Reusable Object-Oriented Software [GHJV95]. This pattern can help keep the inheritance hierarchy relatively flat while providing reasonable extensibility. We’ll explore this pattern, and how traits play a vital role, with an example.
Suppose we want to run different checks on an applicant—credit, criminal records, employment, and so on. We’re not interested in all the checks all the time. An applicant for an apartment may need to be checked for credit history and a criminal record. On the other hand, an applicant for employment may need to be checked for a criminal record and previous employment. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access