Jeremy Hylton : weblog : 2005-03-11

Strategy vs. Hook

Friday, March 11, 2005

A colleague has reminded me a second time that a strategy object is better than a hook method. In principle, I agree, but somehow I fall back to inheritance and hook methods when I actually start to write the code. I must make a more conscious effort to use composition instead of inheritance.

The most recent example was so simple: We need to versions of an object, one with a lock to provide reasonable multi-threaded semantics and one without for applications that want every ounce of performance. I suggested having _lock() and _unlock() methods in the base class and having a subclass that actually provides the lock. The strategy alternative is to call self._lock.acquire() and self._lock.release(), but have _lock be a dummy object in one case.