box ||= Box.new
That won’t do anything as written; the two ‘box’ local variables are
I’m guessing you mean something like this:
@box = box
eb = ErrorBox.new(Box.new)
This is a simple example of the “delegator pattern”: (an instance of)
ErrorBox “has a” Box.
Over time I’ve found myself drawn more and more towards this pattern,
use class inheritance less and less.
For me, the biggest advantage is that you can implement composite
easily. That is, your ErrorBox can contain multiple objects, either
them itself or having them passed in. Its own method ‘x’ can in turn
A#y and B#z as appropriate. Composing systems in this way can make it
clearer what each piece is responsible for.
It allows cleaner decoupling: for example, the ‘foo’ method of Box may
make any sense when inside an ErrorBox, so you don’t delegate it.
Unit testing with mock objects is easy. Your ErrorBox object can have a
Box, and you can easily check that it calls the correct methods on Box.
inheritance you’d end up stubbing or mocking methods on the same object,
which can get messy. Tests are also more robust because they don’t
implementation details of Box.
Finally, there’s more potential for code re-use. One ErrorBox object may
contain a TclBox, whilst another ErrorBox object may contain a QtBox. As
long as they have the same duck-type (e.g. in the above example they
respond usefully to “draw”) then they’ll both work, without code
whereas an ErrorBox which inherits from TclBox will only work with that.
decision as to which to use can even be left until runtime.
Does that answer your question?