Mathias Brandewinder on .NET, F#, VSTO and Excel development, and quantitative analysis / machine learning.
by Mathias 19. September 2010 16:48

fail-owned-translation-failI have been involved recently with a project for a foreign company with offices in the US; the US team receives lots of documents in a foreign language which require translation, and they were interested in a way to speed up the process, using Bing Translator and Google Translate.

Why not just pick one? Both are awesome, but if you have tried them, you know the results can be somewhat random. Having the option to compare their respective results is a good way to make sure you end up with something which makes sense.

This sounded like a perfect case for the Strategy Pattern. I started by defining a common interface:

public interface ITranslator
{
  string TranslateToHindi(string original);
  string TranslateToEnglish(string original);
}

… and implemented two versions, the BingTranslator and the GoogleTranslator, using the API for each of these services. So far so good, but when I started working on the user interface, I ran into a small problem. My user interface has just 2 buttons, “translate to English”, and “Translate to Hindi”, and Ideally, I would have liked to  just pass the specific language pair to use, along these lines:

private void toEnglishButton_Click(object sender, RibbonControlEventArgs e)
{
  ITranslator translator = this.GetTranslator();
  this.TranslateStuff(translator, stuffToTranslate, “en”, “hi”);
}

More...

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.

strategy

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...

Comments

Comment RSS