Update: Corrected terminology – it’s “generic functions” not “generic methods”.
Aside from macros, another nice feature that Lisp supports is mixins. In fact, this is one of the (very, very) few things I miss about C++. Of course, Lisp does it in a much more powerful way using something called generic functions. See here and here for a great description of generic functions in Common Lisp – it’s one of the cooler parts of Lisp, in my opinion, especially for someone like me who has come from a C++/C#/Java OO background.
Although not a tool for every occasion, and somewhat against the spirit of Inherit to Be Reused, Not to Reuse, mixins are nonetheless handy at times. Since mixins are generally implemented via multiple inheritance, they haven’t really been an option in C#…until extension methods came along. Now you can do something like this:
using System;
public interface TellNameMixin
{
string Name { get; }
}public static class MixinImplementation
{
public static void TellName(this TellNameMixin subject, string prefix)
{
Console.WriteLine("My name is: {0}{1}", prefix, subject.Name);
}
}
What we’ve done is to define an interface type and a corresponding extension method that adds functionality to that interface. Since any number of interfaces can be implemented on a type, we can apply our mixin to classes that have no other type relationship, or that already have a base class. Like this:
public class Craig : MarshalByRefObject, TellNameMixin
{
public string Name { get { return "Craig"; } }
}public class Program
{
public static void Main()
{
Craig craig = new Craig();
craig.TellName("Mr. "); // Prints “Mr. Craig”
}
}
The best part about this is – as with all reuse mechanisms – there’s only one place where I have to change how TellName works. Obviously, if the Craig class was the only class I was extending, I could skip the mixin class and just use extension methods directly. But if I have additional types that I want to add this functionality to, and if those classes have no other type relationship (a situation I found myself in just today) then this might be handy.
Anyway, it’s not something you’ll use every day, but it’s worth knowing about.