Speaking of patterns...

A lot of patterns do share a 'trick' that can be hard to grasp for new OO-developers. It's the trick which is made possible by polymorphism: you define a virtual method in a base class B, override it in a derived class D, and suddenly code in class B will call code in class D. To me this sounded confusing at first (hey, I'm raised with Kernighan-Ritchie C, the non-ANSI version, bite me :P). However it's a very neat way to 'plug in' code later (in a derived class) while defining the flow of the code now (in the abstract / base class).

A simple example for the few confused ones might help:


public class B
{
	public void Foo()
	{
		Bar();
	}

	public virtual void Bar()
	{
		Console.WriteLine("B.Bar");
	}
}

public class D:B
{
	public override void Bar()
	{
		Console.WriteLine("D.Bar");
	}
}

Now, when we create an instance of 'D', and call 'Foo', we're actually calling the base class B's method Foo. However, B's code will not call it's own method 'Bar' but will call D's version. For die-hard OO-programmers, this is common knowledge, for new developers arriving in the wonderful world of OO-development (like, hopping over from VB6 to C# ;) ), this is new ground and can result in reactions as "whoa, that's clever". This polymorphism-result forms the basis for many patterns known. It's because of this common OO-knowledge that patterns are thus 'common knowledge', the situation the pattern is used in (the 'semantics') are different from situation to situation, hence the different names.

No Comments