Codelines

Debugging the art of software

Here’s What You Need To Know About .NET Extension Methods

Extension methods are, as the name suggests, a convenient way to extend a class or object’s behaviour by means of external extension. That is, without modifying the class or object directly itself. Extension methods are convenient because they can be used directly on the object or classes they are intended to extend and the extension does not need to be encapsulated in the object it is extending. This is in contrast to utility classes/methods that require you to pass the object in. Here are some guidelines to .NET extension method usage…

Extension methods should be used wisely!

Extension methods, if implemented in too many places at once can make code maintenance more difficult. Realise when is a good time to use an extension method and when you might be better off adding the behaviour directly to the object or class in question. Alternatively a utility class may still be a good choice.

Don’t spread extension methods far and wide

Minimise the amount of files you declare extension methods in. Having a single namespace or ExtensionMethods class will help logically group them together and make it quicker and easier to debug as they won’t be scattered throughout code. In the case of a development team, it may be a good idea to agree upon a core namespace or file to keep most extension methods in for easier code maintenance. Similarly, developers know where to place new extensions. Depending on the project, it may even be worth while agreeing on a core set of extension vocabulary.

Keep extension method usage short and simple

Good candidates for extension methods are those that have few or no parameters. Create well defined behaviour on the object or class. Simple conversion operations, validations etc. are good examples.

// Example validation extensions
 
string emailAddress = "joe.bloggs@fakemail.com";
 
// Extension method on the string class
emailAddress.IsValidEmailAddress(); 
 
string phoneNumber = "03 1234 4567";
postcode.IsValidPhoneNumber();
// Example conversions
 
Person person = new Person
{
    FirstName = "Joe",
    LastName = "Bloggs",
    EmailAddress = "joe.bloggs@fakemail.com"
};
 
// Extension methods to the Person class.
string personAsCSV = person.ToCSV();
Person p = Person.FromCSV(personAsCSV);

Use extension methods to leverage natural behaviour discovery through intelli-sense

One great thing about most common IDE’s these days is out of the box support for intelli-sense. If you are using Visual Studio, hitting ‘Ctrl’ + ‘.’ on an object will bring up it’s method list. This allows a developer to readily discover extensions on the object. This is a big advantage over utility classes or behaviour encapsulated outside the object where if you don’t know they exist, you will likely not use them.

Extension methods have lower precedence than an object or classes own implementation

What this means is that if you extend a class or object with an extension method and at some point in the future this class or object implements your extension, the class/object will no longer continue using your extension method and will opt to use its own method. This is something to be mindful of as you will be given no indication by the compiler that your extension method is not being called. This could be a subtle way to introduce an unintended bug.

Extension method benefits

The real benefit is in being able to extend classes or objects that you have not written or do not have access to the source code to modify directly yourself. This allows you to add functionality to a closed off version of code, third party libraries or even the .NET framework itself! Do you have any experiences you’d like to share with .NET extension methods?

Technorati Tags: ,,

Your Guide To Understanding Language Integrated Query (LINQ) From The Ground Up

Language Integrated Query (LINQ) is quite possibly the greatest technological language advancement since the advent of object-oriented (OO) programming languages. In this post I am going to provide some background and context for what will be a series of posts on many of the underlying features of Language Integrated Query in the .NET framework. By the end of the series you should be aware of, and have a better understanding of, all the different bits and pieces that come together to bring LINQ to the .NET framework.

What is Language Integrated Query (LINQ)?

The evolution of software languages from low level languages like assembly and C up to higher level, more friendly languages like Visual Basic and Java, has shown that the OO paradigm has become a time proven, mature and now taken for granted language paradigm.

Object oriented programming, once considered radical and different with its shift in thinking from functional oriented programming to state and behaviour, is a shift in the way we think about building software; abstracting and encapsulating details into more modular, re-useable bits of code.

Along comes LINQ. In terms of evolutionary programming language advancements, LINQ promises to ease and enhance the way we now, and in the future, produce, consume and integrate with heterogeneous data sources. It achieves this by providing a general purpose declarative querying language (similar to SQL) that can be used on any data source that is made LINQ aware.

Shipping with Visual Studio 2008 Microsoft have provided support for LINQ to SQL, LINQ to XML and LINQ to Entity Classes out of the box. Microsoft are also working on another project (still in its incubation stage at the moment) known as LINQ to XSD; the ability to bind an XSD to an XML file such that entity classes can be generated from typing information found in the XSD file with the intent of providing the developer with a strongly typed XML experience.

So if there is one thing to remember about LINQ it is that LINQ is a general purpose querying language that can work across any information source when it knows what it is and how it can query it (This might be a future post on LINQ providers). No longer do you need specific parsing to read or write that CSV file, XML file, Excel file etc. The productivity increases and potential for LINQ usage is ever increasing as more and more people begin writing LINQ providers to LINQ-enable their data sources.

LINQ Required Features

In future posts I will explore many of the features brought to the .NET framework that have made LINQ possible;

  • Implicitly typed local variables (read: anonymous variables)
  • Lambda expressions and expression trees
  • Extension methods
  • Collection and Object Initializers
  • IEnumerable usage
  • Deferred query evaluation

.NET Language Integrated Query might just change the way you inter-operate with and between heterogeneous data sources by providing a higher level, abstracted querying language that is data source independent. Much like the OO paradigm raised our thinking from functions to objects and state, LINQ will elevate and facilitate fast and efficient interoperability between heterogeneous data sources.

Have you had any experiences with LINQ? What were they and where do you think Microsoft is heading with this brave new technology.

Technorati Tags: ,

Codelines Blogging Back on Track

I’m back! After finishing my Masters thesis on Software Evolution in January I decided to defer my last and final subject whilst I returned to full time work, during which time the company I work for; cvmail, was acquired by Thomson, which later merged with Reuters to become Thomson Reuters. So it has been a busy time with exciting times ahead as we get closer to the launch of our new e-recruitment platform which is built from/sits on top of the latest and greatest of Microsoft’s technology stack; Microsoft SQL Server 2005, .NET 3.5, C# and ASP.NET.

It has been a while since I have had the time to get back into the realm of blogging. But…I am back on track to finish my final subject in my Masters this semester (Enterprise .NET) and am busily working away at work on our new platform. So expect to see plenty of blogging on .NET related technologies as I synchronise my work and study.

Technorati Tags: ,