One of my goals with Fail Tracker is to push the “Convention over Configuration” idea as far as you possibly can within the confines of ASP.NET MVC. I’m obviously biased, but so far I think I’ve been quite successful, and Fail Tracker is probably the most enjoyable codebase I’ve ever worked with. One convention I recently implemented eliminates the need to decorate view model properties with the DisplayNameAttribute. The convention says “Pascal cased property names will be intelligently split into strings with spaces.” Thanks to the infrastructure and pluggable model metadata system that Fail Tracker uses, implementing this convention was quite easy.

But this seemed pointless to me. Why should I have to remember to de-Pascal case my property names every time I created a view model? Fortunately, I don’t have to. Here’s the “model metadata filter” (a feature of the Fail Tracker application framework) that achieves the same thing:

The ToStringWithSpaces extension method is a beautiful piece of Regex that James Kolpack gets credit for:

public static class StringExtensions
{
public static string ToStringWithSpaces(this string input)
{
return Regex.Replace(
input,
"(?<!^)" + // don't match on the first character - never want to place a space here
"(" +
" [A-Z][a-z] |" + // put a space before "Aaaa"
" (?<=[a-z])[A-Z] |" + // put a space into "aAAA" before the first capital
" (?<![A-Z])[A-Z]$" + // if the last letter is capital, prefix it with a space too
")",
" $1",
RegexOptions.IgnorePatternWhitespace);
}
}

And that’s all there is to it. Thanks to the application framework that is baked into Fail Tracker, simply creating the PascalCaseToDisplayNameFilter is all that’s necessary. I can now remove most of my DisplayNameAttributes from my view models. Do note though that the convention is quite easy to override. If I do need to alter the labeling for a property, I can still use the DisplayNameAttribute exactly as before. All my convention does is provide a more reasonable default without getting in the way of doing something different, which is exactly what a good convention should do.

If you want to know more about how these sorts of conventions are automagically wired up in Fail Tracker, feel free to check out Fail Tracker code. I do plan to write much more about the application framework itself, but it may be a while as I’m targeting a magazine publication for that.

About Matt Honeycutt...

Matt Honeycutt is a software architect specializing in ASP.NET web applications, particularly ASP.NET MVC. He has over a decade of experience in building (and testing!) web applications.
He’s an avid practitioner of Test-Driven Development, creating both the SpecsFor and SpecsFor.Mvc frameworks.

He's also an author for Pluralsight,
where he publishes courses on everything from web applications to testing!