Wednesday, May 11, 2011

Where I put my extension code

In a comment on my "ASP.NET MVC - Excluding Model Validation Rules" post reader @wow0609 asked:
Where do you put something like this in your MVC project? This is a specific extension method, probably in a file by itself. Do you have a specific structure (directory / folder) you use for this? Do you have a generic /common folder or something?

I felt this question was worthy of a dedicated post. I break it down this way.

Sharable Code
If the code I've written is not specific to a particular application (as is the case of excluding model validation rules) then I will most likely put it into one of the shared libraries used by my development group.  Those libraries have lots of utility functions and such that are generic to the platform/stack they support.

Application Specific Code
When the code is really only applicable to one application then I'll put it into the application's project.  For a web project I'll typically put them in a class under a "Components" directory.  Often, code will start here and then I'll refactor it to be more generic and move it to a shared library.

In either case, for extension methods I usually name the class/file using this pattern: "[extendedclass]Extensions".  For example: HtmlHelpersExtensions.  I set that class' namespace to the extended class' namespace.  In the case of the MVC model validation rule exclusion extension it would be "System.Web.Mvc".  This eliminates the need to explicitly import/include the custom namespace to discover extension methods which is particularly helpful for shared libraries (or if you are like me and can't remember what you wrote last week).