Sunday, January 31, 2010

How Can Extension Methods Help You?

I am a huge proponent of extension methods in .NET (and other languages).  I believe they are a gateway to making complex code easier to follow and understand, also helps to maintain the object oriented paradigm that .NET is built on. They are also key to the notion of Fluent APIs which has been permeating throughout the programming space for the past year or so.

The idea of a Fluent API is an API that reads very much like an English sentence and is considered a tremendous advancement in readable code.

string value = "500";
int myValue = value.AsInt();

This is a sample code snippet that you see a lot in my projects as I tend to work a library I have created which contains many extension methods for formatting and parsing of values. Notice how as you read the code it flows and its concise with the parsing logic centralized.  Traditionally you might have seen code such as this:

string value = "a500";
int myValue = int.MinValue;
int myValue = int.MinValue;

int.TryParse(value, out myValue);
myValue = Convert.ToInt32(value);

Using TryParse, which is a standard method common to all primitive value types in .NET, this code does not throw an exception and myValue has a value of zero at operations end.  I dont like this because I would expect TryParse to leave the value of myValue unchanged if the parse fails, it does not.  As for the use of Convert it basically emulates what would happen if you called int.Parse on this value, it throws a FormatException.

In addition to the obvious problems of repeating this code anywhere you need to parse an int from a string, I find this to be very procedural.  Now there is no question that all programming, no matter how hard we try is going to be at some level procedural, however, my goal is always to minimize such code and keep things as Object Oriented as possible, after all that is what OO languages are designed for and, not surprisingly, very good at.

Extension methods are also exceptionally useful for custom formatting and outputting for certain types. For example, lets say you wanted to output a DateTime object is standard notation for the United States, mm/dd/yyyy.  Well simply calling ToString(“d”) easily accomplishes this. But littering your code with this code could turn into a potentially horrendous maintenance problem if your boss decides it ought to be dd/mm/yyyy (which is common in Europe), but use an extension method and your code could look like this:

DateTime dt = new DateTime(1983, 1, 13);
Console.WriteLine(dt.AsStandardFormatString());

Using this approach you can have a standard way out outputting a DateTime, perhaps stored somewhere in a different project, that you can easily update, perhaps make culture aware, all without your application ever being the wiser.

So, while Extension Methods are very useful for type conversion libraries and provides standardization out formats and outputs for types, they have another great use. Provides reusable ways to affect changes on objects, collections in particular, while maintaining a very clean interfaces and emphasizing “changes as a unit of work”.  I am sure someone has published something relating to the notion of change as a unit of work, but let me elaborate a little further.

The idea of change as a unit of work derives from the Single Responsibility Principle and Open Closed Principle laid out by Robert Martin.  The idea is that everything has one responsibility and it should carry out that responsibility effectively and thoroughly, from the construction of methods to the definition of classes, they amalgamation of these constructs comprises the application and only by working together can they do such.  Consider the following pieces of code that comes from some code that I wrote this week for a rather complex process that I am working on at work.

var scheduleList = dayList.GroupByShiperId().ConvertToSchedule();

(For those concerned, yes I did mutate this code so that it does not reflect what was actually written).

The idea here is to take a very complicated process and break it down into smaller units and then create functions to carry out those units of work.  Hence any changes to the information is a unit of work.  Easily testable and thanks to extension methods, very clean from an API standpoint. But extension methods are only a small part of this process, understanding the interfaces and classes you have available to you is critical as well as it can help you move code to where it should be.  The method in question could easily have been a 200 line function that would have been a nightmare for anyone to maintain.  Instead its five functions, all with less then 12 lines working together and producing a result.

Using this approach you can be less procedural in your code and leverage the object oriented paradigm of the .NET framework and help people who will come after you understand what is happening. Thus together with good function naming, you can create similar clean reusable APIs for your projects and further leverage the concept of change as a unit of work.

9 comments:

Mike Strobel said...

I tend to discourage the creation of extension methods for common primitive types to avoid "IntelliSense pollution". You might add a small blurb about organizing your extension methods into different namespaces. That way, your extensions aren't imported unless they're needed, and you can import your collection extensions without importing your string extensions, etc.

Anonymous said...

[URL=http://porntube2.org][color=red][b]Watch Free Porn Videos Online (BEST WAY 100% FREE PORN)[/b][/color][/URL]


[url=http://porntube2.org][img]http://porntube2.org/teen.jpg[/img][/url]

Anonymous said...

New here,

I'm spending my time here for the children of Haiti.

I'm doing my part for a non-profit haiti organization that spends their time to
creating oppurtunities for the children in haiti. If anyone wants to donate then then please do so here:

[url=http://universallearningcentre.org]Donate to Haiti[/url] or Help Haiti

They provide children in Haiti books and teach them.

Yes, they're legitimate.

Please help us

Anonymous said...

In today’s rocky economic climate, most households are cutting back wherever they can. I too faced the problem and wated to cut down on
cable tv, I tried P2P, but then not impressed with it. I started collecting ways to watch my favorite tv shows online.
I have listed then in my blogspot, I try to cover as many tv shows and matches as possible, to help others like
me to watch their favorite sports or tv shows online for free.

But my list is not complete, I don't know where to find some international shows, for sports you have numerous resources, Can someone here help me with that?
Please tell me you favorite shows that you watch regularly and also some ideas to cover them. If you need to know the shows that I cover, then visit my blogs

[url=http://tvshows-watch-online-blogspot.com]Watch Online TV Shows for Free[/url]
[url=http://tv-shows-watch-online-blogspot.com]Watch Online Sports for Free[/url]

Anonymous said...

looking an eye to ed drugs? [url=http://www.cahv.org]buy viagra online [/url]and charge out of set free shipping at http://www.cahv.org . another good place to [url=http://www.kiosknews.org]buy viagra online[/url] is www.kiosknews.org .

Anonymous said...

[URL=http://www.wallpaperhungama.in/details.php?image_id=13415][IMG]http://www.wallpaperhungama.in/data/thumbnails/117/Minissha Lamba-91.jpg[/IMG][/URL]

[URL=http://www.wallpaperhungama.in/details.php?image_id=13240][IMG]http://www.wallpaperhungama.in/data/thumbnails/117/Minissha Lamba-90.jpg[/IMG][/URL]

[URL=http://www.wallpaperhungama.in/details.php?image_id=13236][IMG]http://www.wallpaperhungama.in/data/thumbnails/117/Minissha Lamba-87.jpg[/IMG][/URL]

[URL=http://www.wallpaperhungama.in/details.php?image_id=13234][IMG]http://www.wallpaperhungama.in/data/thumbnails/117/Minissha Lamba-85.jpg[/IMG][/URL]


[url=http://www.wallpaperhungama.in/cat-Minissha-Lamba-117.htm][b]Minissha Lamba Sexy Wallpapers[/b][/url]

Photo gallery at WallpaperHungama.in is dedicated to Minissha Lamba Pictures. Click on the thumbnails into enlarged Minissha Lamba pictures, intimate photographs and exclusive photos. Also constraint exposed other Pictures Gallery for Expensive distinction and Momentous Boldness image scans, movie captures, movie promos, wallpapers, hollywood & bollywood pictures, photos of actresses and celebrities

Anonymous said...

The French gourmet cheese Bleu d'Auvergne has a wonderful aroma, a rich taste; the saltiness increases with the incidence of veining. The overall flavor is piquant but not overly sharp. Bleu d'Auvergne started life as an imitation of Roquefort, using cow's milk in place of sheep's milk. Legend has it that a peasant, around 1845, decided to inject his cheese with a blue mold that he found growing on his left-over bread (the motto being, waste not, want not). And thus, the gourmet cheese Bleu d'Auvergne was born. This French gourmet blue cheese comes from the region of Auvergne and the cheese is made from milk of Salers and Aubrac cows. The rind is very thin and so the cheese is usually wrapped in foil. The cheese is rich and creamy with a pale yellow color and scattered holes and well-defined greenish-blue veining. We cut and wrap this cheese in wedge of 8 ounces and 1 pound.

buy fresh blue cheese

[url=http://riderx.info/members/buy_5F00_fresh_5F00_blue_5F00_cheese.aspx]buy fresh blue cheese[/url]

http://riderx.info/members/buy_5F00_fresh_5F00_blue_5F00_cheese.aspx

Anonymous said...

You must have seen Ranbir Kapoor’s wonderful chemistry with Katrina Kaif in Ajab Prem Ki Ghajab Kahani.

Katrina is really exited to romance Ranbir, obviously in reel life. Katrina is really eager to be a part of Ashtvinayak’s next film that casts Ranbir.

However she is well known to this fact that her looks as well as accent can not relate

[url=http://www.wallpaperhungama.in/blog/2010/03/kats-can%E2%80%99t-hold-anymore-to-romance-ranbir-kapoor/]Kats can’t hold anymore to romance Ranbir Kapoor[/url]

[url=http://www.wallpaperhungama.in/blog/]Bollywood News[/url]

Anonymous said...

megan fox shaved hair, [url=http://discuss.tigweb.org/thread/187756]megin fox[/url] megan fox cheerleaders
kim kardashian light hair, [url=http://discuss.tigweb.org/thread/187768]kim kardashian superstar featuring ray j free[/url] kim kardashian picture topless
taylor swift backstage tickets, [url=http://discuss.tigweb.org/thread/187772]taylor swift white horse[/url] taylor swift saturday night live twilight video
lego hannah montana, [url=http://discuss.tigweb.org/thread/187786]hannah montana dareway in us[/url] hannah montana naked pics
drawings of harry potter, [url=http://discuss.tigweb.org/thread/187792]free harry potter sheet music[/url] harry potter and the goblet of fire picture from the movie
cruise to cash and call me, [url=http://discuss.tigweb.org/thread/187798]cruises to the bahamas[/url] carnival triumph cruise to nowhere
jusstin bieber, [url=http://discuss.tigweb.org/thread/187812]justin bieer[/url] justin bieber tour
watch britney spears sex tape iphone, [url=http://discuss.tigweb.org/thread/187814]britney spears latex[/url] britney spears with whip
transformer movie photos of megan fox, [url=http://discuss.tigweb.org/thread/175542]hotter than megan fox[/url] megan fox thumbs