I am looking for a nice reading for students about using delegates instead of inheritance.
By “delegates,” I mean where one might be tempted to provide an abstract class where subclasses fill in the blanks to customize a process, instead the superclass accepts an interface/protocol that a delegate object implements (à la UIKit).
Just the basics. Simple is good.
Anyone know of, say, a blog post or chapter from a book that covers this nicely?
@inthehands This sounds like dependency injection? Is that what you're looking for?
@jenniferplusplus
Not exactly, but related. Underlying mechanism is the same: depend on interface, someone else provides impl.
DI is closely associated with testability, and is often used to replace an A→B dependency that could have been an explicit constructor call from A but instead you hide the impl of B (thus the “injection,” libs to allow swapping impls via configuration, etc).
1/2
@jenniferplusplus The delegate pattern is for A→B patterns where B is tightly coupled to the •client• of A, e.g. A is a table view UI element and B provides the data to show in the table. Think callbacks, but expanded to have multiple entry points and possibly be stateful.
(All hastily explained, hope not totally confusing)
2/2
@inthehands I guess I still don't see what the difference is. If you have some class, like:
class TableView : UIElement
{
new (ITableDataDelegate td)
public void RenderElement()
}
Does that provide the behavior you're looking for?
@jenniferplusplus
For sure! The difference is just intent / vibes. With DI, there’s a whole thing of having some kind of framework that lets you dynamically resolve the implementing class, maybe based on config or whether you’re in test mode or whatever. That whole role of the “injector” does not exist (and doesn’t make sense) for the delegate pattern.
(Problem here may be that DI is an idea that’s drifted a lot, and means many things to many people.)
@jenniferplusplus
Another way to highlight the diff: the alternative to DI is usually an explicit constructor call; the alternative to a delegate is usually an abstract class with a subclass.
@inthehands @jenniferplusplus dependency injection can be done without using frameworks. Nat Pryce shared that in his blog post he usually doesn't use DI frameworks. His book Growing Object Oriented Software might be of interest to you.
http://www.natpryce.com/articles/000783.html
http://www.growing-object-oriented-software.com/