Extension Method? Visitor?
I was reading this really cool article from Scott Hanselman about a newer, smarter way to format objects into a string.
The gist of it is this: you have an extension method called "ToString(..)", with a signature like this:
But then I paused for a minute. I like the reflection and formatting, but what benefit does the extension method bring? Its a parlor trick with a slight syntactic advantage, but it also seems to unnecessarily obfuscate things. To prove my point, I extracted the meat of his code into a simple (read: "less-cool") static method.
In essense, consider the following two lines:
Basically, what I am seeing is that extension methods are a way to implement object visitors, but the actual identity of the visitor is hidden, such that it looks like a native method. I'm still struggling to find out why this is better than writing a plain old explicit visitor. Any opinions?
The gist of it is this: you have an extension method called "ToString(..)", with a signature like this:
public static class FormattableObjectSo what this offer us is a really cool way via reflection to format objects based on their property/field names. For example, consider the basic Person class:
{
...
public static string ToString(this object anObject, string aFormat, IFormatProvider formatProvider)
...
}
public class Personand then you can make a call like:
{
...
public string FirstName{ get; set;}
public decimal Money{get; set;}
}
Person p = new Person(3.43M, "Joe");and the output would look like
Console.WriteLine(p.ToString("{Money:C}, {LastName}"));
3.43, Joe^^Now thats cool! This is a really simple and powerful piece of formatting code!
But then I paused for a minute. I like the reflection and formatting, but what benefit does the extension method bring? Its a parlor trick with a slight syntactic advantage, but it also seems to unnecessarily obfuscate things. To prove my point, I extracted the meat of his code into a simple (read: "less-cool") static method.
In essense, consider the following two lines:
1. Console.WriteLine(p.ToString("{Money:C}, {LastName}"));
2. Console.WriteLine(StringFormattingVisitor.ConvertToString(p, "{Money:C}, {LastName}"));
Now the following two lines of code are functionally equivalent. Call me an old fart, but I like line #2 better, because if theres ever an issue related to the cool string formatting functionality, I can read it and see exactly where the method is defined, the first one abstracts this information away from me.Basically, what I am seeing is that extension methods are a way to implement object visitors, but the actual identity of the visitor is hidden, such that it looks like a native method. I'm still struggling to find out why this is better than writing a plain old explicit visitor. Any opinions?



