by Mathias
9. April 2010 12:04
Learning new things is difficult, but the hardest thing to do is to learn new ways to do things you have always done a certain way. Case in point: the Strategy Pattern. It is the first design pattern I was introduced to, and back then, it was an eureka moment for me.
I learnt it the “classic” way: when a class is performing an operation, but could go about it a few different ways, rather than building a switch statement in the class to handle each particular case, extract an interface for the operation, and create interchangeable concrete implementations, which can be plugged in the “Context” class at run time.

Source: http://www.dofactory.com/Patterns/Patterns.aspx
For some obscure reason, I went to the Wikipedia page dedicated to the Strategy pattern recently, and was very surprised to see that the first C# example proposed didn’t use polymorphism at all. The second example is the old-school interface/concrete implementation version, but the first illustration uses the Func<> delegate. Here is a quick example I wrote using that approach. Rather than an interface, the Strategy can be any function that takes in a string as first argument, and returns a string as a result.
public class Context
{
public Func<string, string> Strategy
{
get;
set;
}
public string SayHello(string name)
{
return this.Strategy(name);
}
}
More...
3f6f2cb9-9f99-4da5-ba0d-8c140a71860f|0|.0
by Mathias
16. January 2010 11:15
One of my recent posts looked into reading the VBA code attached to a workbook, and lead to a discussion on analyzing the differences between the macros of two workbooks – what is commonly called a “diff”.
This got me curious as to how diffs are generated. A quick search lead to the Longest Common Subsequence problem: once (one of) the longest common sub-sequence (abbreviated LCS from now on) of characters between two texts has been identified, it is straightforward to determine what has been added and removed from the original text to get the second text.
Example
Original: this is my great code
Modified: that is my awesome code
LCS: th is my code
Changes to original: this is my great code
The idea behind the algorithm used to identify such a longest common subsequence (LCS) is a nice example of dynamic programming, and goes along these lines. If I have two sequences,
- if they start with the same character (the head), then their LCS is the head + the LCS of the right-hand remainder of each string (the tail),
- if they don’t start with the same character, then their LCS could start either with the head of the first sequence, or of the second one. Their LCS is the longest of the LCS of the first sequence and the tail of the second, and of the LCS of the second sequence and the tail of the first one.
More...
0a186791-19e1-46aa-8050-5342d73400a2|2|5.0