When setting out good design, which would you choose, extension methods or the visitor pattern?.
Which is easier to design for, when should you use an extension method over a visitor pattern and vice verso?
Is there any good valid reason to use an extension method over a visitor class, apart from syntactical sugar to aid in program readability?
How would you design for a system that incorporates extension methods, would you classify them in a UML diagram?
namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
I may have the wrong pattern, it looks like a visitor pattern from the code above. So I think my comparison holds up.
Some code, I would say that the extension method looks like a visitor pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
#region Interfaces
public interface IFred
{
string Data
{
get;
set;
}
string doSomething();
}
public interface IBob
{
string Data
{
get;
set;
}
}
#endregion
#region fred stuff
public partial class Fred : IFred
{
public string doSomething()
{
return this.Data + " is really cool";
}
public string Value()
{
throw new NotImplementedException();
}
}
public partial class Fred
{
public string Data
{
get;
set;
}
}
#endregion
#region bob stuff
public class BobData : IBob
{
public string Data
{
get;
set;
}
}
public class BobData2 : IBob
{
private string pData;
public string Data
{
get
{
return pData + " and then some!";
}
set
{
pData = value;
}
}
}
public class BobVisitor
{
public string dosomething(IBob bobData)
{
Console.WriteLine(bobData.Data);
return "ok";
}
public string dosomethingOnlyToBob(BobData bobData)
{
Console.WriteLine("hello bob version 1");
return "ok";
}
public string dosomethingOnlyToBob2(BobData2 bobData)
{
Console.WriteLine("hello bob version 2");
return "ok";
}
}
#endregion
public static class Visitor
{
public static string visit(this IBob bobObj)
{
Console.WriteLine(bobObj.Data);
return "ok";
}
public static string visit(this IFred fredObj)
{
Console.WriteLine(fredObj.Data);
return "ok";
}
}
class Program
{
static void Main(string[] args)
{
//Another way of abstracting methods from data, using Partial Classes.
var fredObj = new Fred();
fredObj.Data = "fred data";
fredObj.doSomething();
//Create the bob classes version 1 and 2
var bobObj = new BobData();
bobObj.Data = "bob data";
var bob2Obj = new BobData2();
bob2Obj.Data = "bob 2 data";
//using the bobVisitor Class
var bobVisitor = new BobVisitor();
bobVisitor.dosomething(bobObj);
bobVisitor.dosomething(bob2Obj);
bobVisitor.dosomethingOnlyToBob(bobObj);
bobVisitor.dosomethingOnlyToBob2(bob2Obj);
//using the extension methods in the extension class
bobObj.visit();
fredObj.visit();
Console.Read();
}
}
}