Non-generic Wrapper instead of Base Class or Interface

A common solution to treating a generic type as non-generic is to implement an interface or make the generic type extend from a non-generic base class. Among other reasons, this allows you to instantiate a collection of generic types. There are varying implementations of this pattern, but they all seem to share this common strategy. In this article I present an alternate approach favoring composition over inheritance which I argue is more appropriate in circumstances where the intent is to break type safety.

To clarify, I will follow Steven Lowe’s argumentation on misuse of inheritanceSemantically, the statement “SomeType<T> is SomeType” is not always true; SomeType<T> is not a proper subtype of SomeType when the base type exposes type-specific bits (as Jon Skeet puts it). In this case the extending type imposes more restrictions than the base type. When there is a need to expose type-specific bits (implying type casts are involved), using inheritance does not follow the Liskov substitution principle (LSP). Regardless, such subtypes seem common. Just consider Microsoft’s List<T> implementing a non-generic IList which to quote Eric Lippert, “is a bit odd, since List for any type other than object does not fulfill the full contract of IList”.

From this it becomes clear there are real-world scenarios where a generic type needs to be accessed in a non-generic way (e.g. during reflection as I argued previously). Type safety is temporarily broken, leaving it is up to the caller to guarantee only the correct types are used. How then to improve on the following common implementation? Note that since the non-generic interface is implemented explicitly, the caller consciously needs to cast to ISomeType, somewhat alleviating the problem of possible misuse.

public interface ISomeType
{
    object Value { get; set; }
}

public class SomeType<T> : ISomeType
{
    public T Value { get; set; }

    // Explicit implementation (cast to ISomeType needed to be used).
    object ISomeType.Value
    {
        get { return this.Value; }
        set { this.Value = (T)value; }
    }
}

We need a non-generic interface but are given a generic interface, so why not apply the adapter pattern?

An adapter helps two incompatible interfaces to work together. […] Interfaces may be incompatible but the inner functionality should suit the need.

Since the class we are trying to create an adapter for is generic, our adapter implementation needs to be generic too. However, we can expose the non-generic interface which will be used by the client. Just like a usual adapter, the non-generic wrapper contains the adaptee and refers all of the IAdaptor calls to it, casting to T where necessary.

public interface IAdaptor
{
    object Value { get; set; }
}

class NonGenericWrapper<T> : IAdaptor
{
    private readonly Adaptee<T> _adaptee;

    public NonGenericWrapper(Adaptee<T> adaptee)
    {
        _adaptee = adaptee;
    }

    public object Value
    {
        get { return _adaptee.Value; }
        set { _adaptee.Value = (T) value; }
    }
}

Furthermore, to facilitate the creation of this non-generic wrapper (and in addition hiding its implementation) the wrapper can optionally be initialized from within the adaptee and added as a member. This approach seems similar to how user interface controls in .NET expose the window handle they operate on as a member variable, allowing for unsafe operations when the control class does not offer the required functionality.

public class Adaptee<T>
{
    public T Value { get; set; }

    public IAdaptor NonGeneric { get; private set; }

    public Adaptee()
    {
        NonGeneric = new NonGenericWrapper<T>(this);
    }
}
Pattern which can be used to expose a non-generic interface from within a generic class.
Pattern which can be used to expose a non-generic interface from within a generic class.

This approach still requires boiler-plate code to be written and maintained (NonGenericWrapper<T>), but no longer breaks the Liskov substitution principle. Ideally creating non-generic wrappers can be automated, of which I created an early prototypical solution before (not functional in all scenarios). Until then, this solution provides a more robust implementation for complex scenarios using generics, like collections of generic types with varying type parameters on which the same operations need to be performed. This might be the topic of a future post.

Generic TypeConverter for XAML

TypeConverter‘s in WPF are part of the underlying mechanism which allow you to assign values to attributes of complex types within XAML using plain strings. For example, whenever you specify Point‘s.

<LinearGradientBrush StartPoint="0,0" EndPoint="1,1" />

Typically, you specify a TypeConverter for a certain type by applying the TypeConverterAttribute to it.

[TypeConverterAttribute( typeof( PointConverter ) )]
public struct Point : IFormattable

Since attribute arguments cannot use type parameters, this prevents you from specifying a generic TypeConverter for a generic class. I came across this issue while implementing a type converter to support specifying instances of my generic Interval class from XAML. The following is not possible.

// attribute argument cannot use type parameters
[TypeConverter( typeof( IntervalTypeConverter<T, TSize> ) )]
public class Interval<T, TSize>

However, you can write a non-generic TypeConverter which is capable of converting strings to several different target types. When using XAML you can obtain a IDestinationTypeProvider service through the context which is passed to the ConvertFrom method. From here you can retrieve the fully specified target type, including generic type parameters. Through reflection you can then call a Parse method on the specific type to take care of initializing an instance of the desired type. An example for Interval can be found in my library.

public override object ConvertFrom(
    ITypeDescriptorContext context,
    CultureInfo culture,
    object value )
{
    var typeProvider =
      (IDestinationTypeProvider)context.GetService( typeof( IDestinationTypeProvider ) );
    Type targetType = typeProvider.GetDestinationType();

    // ... convert to desired target type using a parsing method

    return base.ConvertFrom( context, culture, value );
}

However, it is important to note that this type provider will only work for XAML, since the IDestinationTypeProvider service is only provided by XAML’s ServiceProviderContext. It is thus not desirable to add this TypeProvider to types which work independent from XAML, like my Interval class. In addition this would require referencing the System.Xaml assembly.

How then to make XAML use this type provider without applying the attribute to the type definition? One option is applying the TypeConverter attribute on a per-property basis.

The per-property type converter technique is particularly useful if you choose to use a property type from Microsoft .NET Framework or from some other library where you cannot control the class definition and cannot apply a TypeConverterAttribute there.

However, this implies a lot of redundancy, having to apply the attribute to every property of that specific type. Using TypeDescriptor.AddAttributes() you can assign a TypeConverter at runtime.

TypeDescriptor.AddAttributes(
  typeof( Interval<,> ),
  new TypeConverterAttribute( typeof( IntervalTypeConverter ) ) );

Any subsequent TypeDescriptor.GetConverter() call will then return the converter for the specified type. Unfortunately this does not work for XAML, since XAML does not seem to take component modifications at runtime into account. Therefore, in order for this to work, we need to implement this runtime behavior ourselves. Recall that XAML does load TypeConverter‘s specified in TypeConverterAttribute‘s. We can thus use a special type converter which redirects its implementation to a converter loaded through TypeDescriptor to hook into XAML’s type conversion runtime. I implemented a RedirectTypeConverter which can be used as a base class for this exact purpose. Each of its methods first ensures the converter is initialized using TypeDescriptor, and then redirects the call to this converter. When TypeDescriptor.GetConverter( _type ) returns the redirecting type converter itself, this means no converter was specified using TypeDescriptor, hence no conversion is supported for this type.

protected RedirectTypeConverter( Type type )
{
	_type = type;
}

public override object ConvertFrom(
	ITypeDescriptorContext context,
	CultureInfo culture,
	object value )
{
	InitializeConverter();
	return _converter.ConvertFrom( context, culture, value );
}

public void InitializeConverter()
{
	if ( _converter != null )
	{
		return;
	}

	_converter = TypeDescriptor.GetConverter( _type );
	if ( _converter.GetType() == GetType() )
	{
		string message = string.Format(
		  "Conversion failed. Converter for {0} is missing in TypeDescriptor.", _type );
		throw new InvalidOperationException( message );
	}
}
class RedirectIntervalTypeConverter : RedirectTypeConverter
{
	public RedirectIntervalTypeConverter()
		: base( typeof( Interval<,> ) )
	{
	}
}

Applying this converter using TypeConverterAttribute to generic types thus allows redirecting type conversion to a converter which supports multiple target types in environments which provide information about the target type (like XAML using IDestinationTypeProvider). You only need to add the converter once, and it will be supported for all of your dependency properties using them.

TypeDescriptor.AddAttributes(
  typeof( Interval<,> ),
  new TypeConverterAttribute( typeof( IntervalTypeConverter ) ) );

Interval: Generic Ranges in C#

There is no doubt about it; out of all the programming languages I ever experimented with, C# has offered me the most streamlined positive development experience so far. It is a modern, ever-evolving language, which now that C# and the whole .NET framework is turning to open source, is guaranteed an even greater future. However, some core constructs commonly available in other languages, like intervals which I introduce an implementation of in this post, are missing. E.g., Ruby has had Ranges for quite some time.

A Range represents an interval—a set of values with a beginning and an end.

Straightforward, but due to the lack of support for generic calculations in C#, a hassle to implement. However, as introduced by Marc Gravell, with some runtime compilation trickery involving expression trees, far from out of reach. I’ve had an Interval class within my core library for quite some time, but just now refactored it to also support more complex intervals, e.g. an interval between two DateTime instances, which thus represents a TimeSpan.

Without further ado, an example of what using this looks like in practice.

// Mockup of a GUI element and mouse position.
var timeBar = new { X = 100, Width = 200 };
int mouseX = 180;

// Find out which date on the time bar the mouse is positioned on,
// assuming it represents whole of 2014.
var timeRepresentation = new Interval<int>( timeBar.X, timeBar.X + timeBar.Width );
DateTime start = new DateTime( 2014, 1, 1 );
DateTime end = new DateTime( 2014, 12, 31 );
var thisYear = new Interval<DateTime, TimeSpan>( start, end );
DateTime hoverOver = timeRepresentation.Map( mouseX, thisYear );

// If the user clicks, zoom in to this position.
double zoomLevel = 0.5;
double zoomInAt = thisYear.GetPercentageFor( hoverOver );
Interval<DateTime, TimeSpan> zoomed = thisYear.Scale( zoomLevel, zoomInAt );

// Iterate over the interval, e.g. draw labels.
zoomed.EveryStepOf( TimeSpan.FromDays( 1 ), d => DrawLabel( d ) );

As you might notice, the timeRepresentation interval has just one generic parameter (Interval<int>), whereas thisYear has two (Interval<DateTime, TimeSpan>). The less generic (one type parameter) class is a simple wrapper around the more generic base type which has two type parameters; the first denotes the type used to represent any position within the range, whereas the second type is used to represent differences between these positions. When these types are the same, the simplified wrapper can be used. Likewise, a TimeInterval wrapper can easily be created if you find Interval to be too verbose.

Worth noting here to understand how it works under the covers is the constructor which sets two public static fields used during operations when conversions to double are needed. Arguably, this could be improved by having a factory creating the intervals and using constructor injection instead.

public TimeInterval( DateTime start, bool isStartIncluded, DateTime end, bool isEndIncluded )
	: base( start, isStartIncluded, end, isEndIncluded )
{
	ConvertDoubleToSize = d => new TimeSpan( (long)Math.Round( d ) );
	ConvertSizeToDouble = s => s.Ticks;
}

Once you start incorporating the notion of an interval in your programming arsenal you will be amazed by the opportunities which present themselves where to use them! Some actual examples within my core library:

To get an impression of the full range of currently supported operations, check out the unit tests.

Generic Attributes in C#

As awesome as C# is, once you want to do some more advanced stuff with attributes, you quickly run into several limitations. There is even a Microsoft Connect entry on this issue.

  • Attributes can’t be generic, since a generic type cannot derive from ‘Attribute’.
  • An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

Using TypeDescriptor and a whole bunch of custom code these limitations can be overcome. In this post I will describe an easier straightforward way by which to create something similar to generic attributes, ignoring the second issue for now. In future posts I will discuss how and where these attributes can be used for something I previously called attribute metabehavior.

The idea is quite straightforward; although attributes can’t be generic, nothing prevents you from adding generic instances to them. These instances can later be extracted at run time using reflection. The trick of course is initializing the generic instance. Once you know the Activator class can create instances by knowing their Type definition, the solution becomes self-evident. By simply passing the generic type as an argument to the attribute, instance creation can be delegated to Activator. Optional constructor arguments can also be passed as attribute arguments.

public class BehaviorAttribute : Attribute
{
	/// <summary>
	///   The dynamically created instance of the type passed to the constructor.
	/// </summary>
	public object DynamicInstance { get; private set; }

	/// <summary>
	///   Create a new attribute and initialize a certain type.
	/// </summary>
	/// <param name = "dynamicType">The type to initialize.</param>
	/// <param name = "constructorArguments">
	///   The arguments to pass to the constructor of the type.
	/// </param>
	public BehaviorAttribute(
		Type dynamicType,
		params object[] constructorArguments )
	{
		DynamicInstance =
			Activator.CreateInstance( dynamicType, constructorArguments );
	}
}

This attribute can then be be applied as follows:

class Answer<T>
{
	public T Value;

	public Answer( T value )
	{
		Value = value;
	}
}

[BehaviorAttribute( typeof( Answer<int> ), 42 )]
class TheWorld {}

Using ordinary reflection, the instance can be extracted.

Type type = typeof( TheWorld );
var behavior = (BehaviorAttribute)type
    .GetCustomAttributes( typeof( BehaviorAttribute ), false ).First());
var genericInstance = (Answer<int>)behavior.DynamicInstance;
int answer = genericInstance.Value;

What follows is up to you, how will you use this? I’ll describe a few advanced use cases in subsequent posts.

Casting to less generic types

… because yes, there are valid use cases for it! Finally I found the time to write some unit tests, followed by fixing the remaining bugs, and am now excited to report on the result which effectively allows you to break type safety for generic interfaces, if you so please. Previously I discussed the variance limitations for generics, and how to create delegates which overcome those limitations. Along the same lines I will now demonstrate how to overcome those limitations for entire generic interfaces.

Consider the following interface which is used to check whether a certain value is valid or not.

public interface IValidation<in T>
{
    bool IsValid( T value );
}

Notice how T is made contravariant by using the in keyword? Not only values of type T can be validated, but also any extended type. This recent feature of C# won’t help a bit in the following scenario however. During reflection you can only use this interface when you know the complete type, including the generic type parameters. In order to support any type, you would have to check for any possible type and cast to the correct corresponding interface.

object validator;  // An object known to implement IValidation
object toValidate; // The object which can be validated by using the validator.

if ( validator is IValidation<string> )
{
    IValidation<string> validation = (IValidation<string>)validator;
    validation.IsValid( (string)toValidate );
}
else if ( validator is IValidation<int> )
{
    IValidation<int> validation = (IValidation<int>)validator;
    validation.IsValid( (int)toValidate );
}
else if ...

Hardly entertaining, nor maintainable. What we actually need is covariance in T, or at least something that looks like it. We want to treat a more concrete IValidation<T> as IValidation<object>. For perfectly good reasons covariance is only possible when the type parameter is only used as output, otherwise objects of the wrong type could be passed. In the given scenario however, where we know only the correct type will ever be passed, this shouldn’t be a problem.

The solution is using a proxy class which implements our less generic interface and delegates all calls to the actual instance, doing the required casts where necessary.

public class LessGenericProxy : IValidation<object>
{
    readonly IValidation<string> _toWrap;

    public LessGenericProxy( IValidation<string> toWrap )
    {
        _toWrap = toWrap;
    }

    public bool IsValid( object value )
    {
        return _toWrap.IsValid( (string)value );
    }
}

With the power of Reflection.Emit, such classes can be generated at runtime! RunSharp is a great library which makes writing Emit code feel like writing ordinary C#. It’s relatively easy (compared to using Emit) to generate the proxy class. The end result looks as follows:

object validator;  // An object known to implement IValidation
object toValidate; // The object which can be validated by using the validator.

IValidation<object> validation
    = Proxy.CreateGenericInterfaceWrapper<IValidation<object>>( validator );

validation.IsValid( toValidate ); // This works! No need to know about the type.

// Assuming the validator validates strings, this will throw an InvalidCastException.
//validation.IsValid( 10 );

Of course the proxy should be cached when used multiple times. Originally I also attempted to proxy classes instead of just interfaces by extending from them. This only works properly for virtual methods. Since non-virtual methods can’t be overridden there is no way to redirect the calls to the required inner instance.

Source code can be found in my library: Whathecode.System.Reflection.Emit.Proxy.

Casting generic types

There, I did it! I dared to leave out covariance and contravariance from the title while that’s the very subject. Why? Because it isn’t important to know exactly what they mean and I still find those terms confusing. As a matter of fact, I won’t mention them again. If you want to know how they relate to the discussed subject, read Eric’s excellent description on the actual meaning of them. This is an introductory post to a few follow-up posts relating to the subject, so more is on the way!

You wouldn’t be reading this if you weren’t acquainted with inheritance, and probably you know about generics, so let’s start from there.

Step 1: Cats and dogs

Cats and dogs are animals.

class Animal { }
class Dog : Animal { }
class Cat : Animal { }

This allows you to safely do the following implicit casts, no big deal.

Cat cat = new Cat();
Dog dog = new Dog();
Animal animal = cat;
animal = dog;

Step 2: Pets

Cats and dogs make excellent pets, so let’s use the following generic approach.

class Pet<T>
    where T : Animal
{
    readonly T _animal;

    public Pet( T animal )
    {
        _animal = animal;
    }

    public T RunAway() { return _animal; }
    public PlayWith( T friend ) { }
}

Notice how pets can only play with animals of their own kind. Regardless of the cute picture above, this means cats and dogs don’t get along, and can’t play together. When a pet runs off, it is no longer a pet, but just an animal.

Pet<Dog> dog
  = new Pet<Dog>( new Dog() );
Pet<Cat> cat
  = new Pet<Cat>( new Cat() );
// Not possible!
// dog.PlayWith( cat );

Of course, pet dogs can still play with dogs, and pet cats with cats.

Step 3: Stray pets

The delegate representation of a method returning an object and taking no arguments is Func. Pet.RunAway is exactly such a method, returning generic type T.

Pet<Dog> dog = new Pet<Dog>( new Dog() );
Func<Dog> runAway = dog.RunAway;
Dog strayDog = runAway();

Programming is all about abstractions. When a pet runs off, is there always a need to know what kind of animal it is? The answer is no, any pet that runs off is certain to be an animal. You can easily do the following starting from .NET 4.0.

Func<Animal> runAwayDog = dog.RunAway;
Func<Animal> runAwayCat = cat.RunAway;
Animal strayAnimal = runAwayDog();
strayAnimal = runAwayCat();

Func<Animal> oldWay = () => dog.RunAway();  // Prior to .NET 4.0 this was possible using a lambda.

The same assumption can’t be made about the Pet.PlayWith method. I already demonstrated dogs can’t play with cats, so we can’t generalize dogs can play with any animal. So what is different about PlayWith? First, I need to introduce you to bulldogs.

Step 4: Bulldogs

Bulldog

class Bulldog : Dog { }
...
var bulldogPet
  = new Pet<Dog>( new Bulldog() );
var dogPet
  = new Pet<Dog>( new Dog() );

// All dogs like each other ...
dogPet.PlayWith( new Bulldog() );
bulldogPet.PlayWith( new Dog() );

A bulldog is a dog, but a dog isn’t always a bulldog. However, a bulldog is a dog, and any dog can play with any other dog, regardless of its kind. The following delegate casts are possible in .NET 4.0. Action represents a delegate with a single argument of type T but no return value.

 

Action<Dog> play = dog.PlayWith;
Action<Bulldog> bullDogPlay = play; // If dogs can get along, bulldogs can get along as well.

Action<Bulldog> oldAction = friend => play( friend );    // Prior to .NET 4.0 using a lambda.

Step 5: In and out

The conclusion is we can only make assumptions about types based on the interaction it is used in. Two interactions can be distinguished.

  • Input: A type is used as input into the class. (e.g. function argument) The type can be the same type, or any extending type.
  • Output: A type is returned from a class. (e.g. return value) The type should be the same type, meaning it is also any base type of that type.

The problem with generics is the type parameters can be used both as input and output, so an upcast to a ‘less’ generic type isn’t possible.

Pet<Dog> dog = new Pet<Dog>( new Dog() );
Pet<Cat> cat = new Pet<Cat>( new Cat() );
// Not possible ...
// Pet<Animal> dogAnimal = dog;
// Pet<Animal> catAnimal = cat;
// dogAnimal.PlayWith( catAnimal );  // Dogs don't play with cats!

But, what if you can guarantee a template argument will only be used as input, or will only be used as output? .NET 4.0 allows you to indicate this on generic interfaces and delegates by using the in and out keywords. It is these keywords which allow the aforementioned casts of the Action and Func delegates. A decision was made to leave this feature out for generic classes, since there are little useful scenarios for it.

As an example for our pets, the following is an interface where the generic type is only used as output.

interface IPet<out T>
{
    T RunAway();
}

class Pet<T> : IPet<T>
    where T : Animal
{
    ...
}
...
IPet<Dog> dog = new Pet<Dog>( new Dog() );
IPet<Animal> animal = dog;  // The generic interface can be upcasted!

Is this still not flexible enough for your purposes? Be sure to follow my next few posts which will discuss useful workarounds in scenarios where more assumptions can be made, more specifically during reflection.

Interpolation no more

Mathematics isn’t my forte. That’s why each time I have to implement some form of interpolation, I feel a headache coming up. Even simple linear interpolation has been bugging me, as it’s the same thing over and over again. One of the beauties of software development is you can write something once, and as long as it works, you don’t have to worry about it anymore. Why then, have I already implemented interpolation for around 5 different data types? My latest need for interpolation, I finally decided to put some effort into this bugger and solve it once and for all.

Armed with a recently discovered library which allows usage of generics for calculations in C#, I managed to come up with the following classes.

Abstract interpolation class diagram.

Implementations of AbstractInterpolation decide on the type of interpolation between certain key points. How key points should be interpreted is decided by the implementation of AbstractKeyPointCollection. The difference between the two implementations will be demonstrated later. In order to know what to interpolate (the TValue template parameter), a trivial implementation of  AbstractTypeInterpolationProvider is required for the type which needs to be interpolated. All classes have a base class AbstractBasicArithmetic, which allows to do basic arithmetic operations on the specified template type TMath. This type determines the value type to use, and return for the calculations of the interpolation. They are done through a ‘Calculator‘ object, as specified in the generic calculations article. Normally you have to pass this calculator object yourself, but I created a CalculatorFactory which creates the corresponding correct calculator for known value types like double.

Perhaps, to better understand the design, a code sample is easier to demonstrate. Consider the desired result pictured in the following image. Of course to achieve drawing simple lines, better solutions exist, but for demonstration purposes, this works really well. The subsequent code sets up some points to interpolate between, and the interpolation which will be used.

CumulativeKeyPointCollection<Point, double> keyPoints = new
    CumulativeKeyPointCollection<Point, double>( new PointInterpolationProvider() );

keyPoints.Add( new Point( 50, 50 ) );
keyPoints.Add( new Point( 100, 100 ) );
...
keyPoints.Add( new Point( 300, 330 ) );

LinearInterpolation<Point, double> linear = new LinearInterpolation<Point, double>( keyPoints );

CumulativeKeyPointCollection is chosen instead of AbsoluteKeyPointCollection, because every key point added to the collection ‘continues’ on the previous point. The line needs to go through the points in the order in which they were added. When using AbsoluteKeyPointCollection, every key point has an absolute position. It doesn’t matter in which order the key points are added. E.g. Interpolating between known locations at specified times, where time is then used as the absolute position.

Next, some interpolated points are calculated as follows.

List<Point> interpolatedPoints = new List<Point>();
double curPercentage = 0;
while ( curPercentage < 1 )
{
    interpolatedPoints.Add( linear.Interpolate( curPercentage ) );
    curPercentage += 0.001;
}

And that’s how easy interpolation can be! To achieve the result as pictured earlier, I just draw line segments between all the calculated points, and draw rectangles on top of the key points. All that remains for the code to work, is the type provider for Point which was passed to the key point collection. As you can see, that’s just a simple implementation of AbstractTypeInterpolationProvider.

    /// <summary>
    ///   Allows AbstractInterpolation to interpolate over a list of points.
    /// </summary>
    public class PointInterpolationProvider : AbstractTypeInterpolationProvider<Point, double>
    {
        /// <summary>
        ///   Create a new provider to allow AbstractInterpolation to interpolate
        ///   between a list of points.
        /// </summary>
        public PointInterpolationProvider()
            : base( 2 )  // The amount of dimensions this type has.
        {
        }

        protected override double GetDimensionValue( Point value, int dimension )
        {
            switch ( dimension )
            {
                case 0:
                    return value.X;
                case 1:
                    return value.Y;
                default:
                    throw new NotSupportedException(
                        "Unsupported dimension while doing interpolation on type " +
                        typeof(Point) + "." );
            }
        }

        public override double RelativePosition( Point from, Point to )
        {
            // Pythagoras to get distance.
            return Math.Sqrt( Math.Pow( to.X - from.X, 2 ) + Math.Pow( to.Y + from.Y, 2 ) );
        }

        public override Point CreateInstance( double[] interpolated )
        {
            return new Point( interpolated[ 0 ], interpolated[ 1 ] );
        }
    }

To show the flexibility of this approach, cardinal spline interpolation is possible by just changing the used LinearInterpolation class to CardinalSplineInterpolation.

CardinalSplineInterpolation spline =
    new CardinalSplineInterpolation( keyPoints );

Every time I need to implement something a bit more mathematically challenging, and search for help, I seem to end up on web pages created during the Middle Ages of the internet. Aren’t there any reuseable libraries out there which support e.g. interpolation out of the box on the actual types you want to perform it on? Like Point in the before given sample. I experience that so many libraries implement concrete implementations instead of generic solutions. For the interpolation to work I had to implement a generic binary search algorithm because SortedList (used to store the key points) didn’t support a binary search out of the box. To indicate intervals of values I had to create a generic Interval class, which I immediately could use in other source files as well. All this, of course brings some overhead with it. Instead of Donald Knuth‘s famous “premature optimization is the root of all evil” quote, I find Bill Harlan’s succinct expression even better.

It is easier to optimize correct code than to correct optimized code. – Bill Harlan

Source code can be found as part of my FCL Extension library in the Whathecode.System assembly and namespace Whathecode.System.Arithmetic.Interpolation.

Java Generic Observer

Design patterns, you gotta love them! What would we do without our beloved Observer Pattern? Since its usage is so common, most frameworks provide an implementation out of the box. Microsoft even added a language construct for it to C#, called ‘events‘. As a Java developer, it would seem you are less lucky. Through the years, my unconditional trust in the design of frameworks has been wavering. Java’s default implementation of the Observer pattern is a nice example of what I consider bad design. Perhaps that’s why it’s not even used in the framework itself. (ActionListener in awt)

If you haven’t watched “Despicable Me” yet, stop reading and watch it first! 😉 It’s a great movie. Consider a person (Gru) needing the ability to watch over his minions.

A standard implementation using the framework’s classes would be:

Gru gru = new Gru();
Minion fred = new Minion();
fred.addObserver(gru);
fred.moo();

public class Minion extends Observable
{
    public void moo()
    {
        setChanged();
        notifyObservers("hehehe");
    }
}

public class Gru implements Observer
{
    public void punch(Minion minion) { ... }

    @Override
    public void update(Observable o, Object arg)
    {
        if (o instanceof Minion)
        {
            String s = (String)arg;
            if (s.equals("hehehe"))
            {
                punch((Minion)o);
            }
        }
    }
}

The thing that bothers me (and others) in this implementation is the need for type checking. After browsing around, I found an implementation by Allain Lalonde who addressed this issue by using a dynamic proxy. I found his solution to be really useful, implemented it, and added a small feature which allows extending from a generic AbstractObservable class. The result looks as follows:

Gru gru = new Gru();
Minion fred = new Minion();
fred.addObserver(gru);
fred.moo();

public interface IMinionListener
{
    public void laughing(Minion minion);
}

public class Minion extends AbstractObservable<IMinionListener>
{
    public void moo()
    {
        getEventDispatcher().laughing(this);
    }
}

public class Gru implements IMinionListener
{
    public void punch(Minion minion) { ... }

    public void laughing(Minion minion)
    {
        punch(minion);
    }
}

How it works.

Events are dispatched through an ObserverPool as described by Allain Lalonde. This is a proxy class which forwards calls (as defined by the interface) to a set of listeners, the observers. You can use this pool directly, or extend from AbstractObservable which already creates and wraps it for you.

Possible problems.

As with the original Observable, you might not be able to extend from AbstractObservable since multiple inheritance isn’t allowed. You could use composition instead, and use the IAbstractObservable interface.

AbstractObservable source code

Better solution? (most likely)

I wrote this code a while ago, before I started this blog. While writing, I followed a link on Wikipedia which I wish I found before. It seems there is a free package available called PerfectJPattern, containing componentized design patterns, including the observer pattern. From the looks of it, they also use a proxy approach. The project looks really well maintained, clean, and thoroughly implemented. Next time I develop in Java, I’ll check it out.