Beyond Abstract classes

Submitted by Larry on 7 January 2014 - 1:18am

Recently, Anthony Ferrara has been posting a periodic "Beyond" series about software design philosophy. Some in particular have hinted at concepts I've been pondering as well. With his blessing, therefore, consider this a continuation of that series.

PHP 5.4 is not exactly new, but it's finally starting to see actual usage by a decent number of people. Its most notable new feature is Traits, which in PHP are implemented as, essentially, compile-time copy-paste. Conceptually, though, they're a way to mix functionality into a class without using inheritance, and without requiring a separate distinct object for composition. (At least in PHP; the term "trait" appears in other languages for similar but subtly different tools.) That's not to say that they're a surrogate for composition; they most certainly are not. They serve a different purpose, that is, providing code for a class to reuse without using inheritance.

Recently, I was reading an article discussing the implementation of inheritance, such as it is, in Go, Rust, and other new-wave concurrent languages. (Thanks to twistor for helping me track down the link.) It made an interesting point that crystallized for me why it is I am so excited about traits. Specifically, it noted that there are not one but two kinds of code reuse: interface reuse and code reuse.