ELMAH and Exception Driven Development FTW
Jeff blogged last month about Exception-Driven Development. I've been using ELMAH for years and you should too. Having great instrumentation in your app is such a joy. I added ELMAH to NerdDinner and have learned all sorts of things. It's amazing that someone would care to hack a site about Nerds eating dinner, but they try.
This wasn't a hack, but a great bug found in my Nerd Dinner Mobile code that I wouldn't have thought to look for. Here I'm getting a NullReference Exception...why?
Well, here's the code:
private bool UserAgentIs(ControllerContext controllerContext, string userAgentToTest)
StringComparison.OrdinalIgnoreCase) > 0);
Of course, I'm breaking the "
Law Suggestion of Demeter" with all that digging, but what's the real issue? I'm assuming that the request has a UserAgent string at all! Exactly as the YSOD that ELMAH "tivo'ed" for me above.
So I changed it to this. Yes, I know that this could all be on one line and really baroque, but I find a few more lines to be easier to read.
public bool UserAgentIs(ControllerContext controllerContext, string userAgentToTest)
string UA = controllerContext.HttpContext.Request.UserAgent;
if (string.IsNullOrEmpty(UA) == true)
return (UA.IndexOf(userAgentToTest, StringComparison.OrdinalIgnoreCase) > 0);
I likely would have never thought of this bug had I not had logs and instrumentation. A smart user could have told me, or I could have used a Unit Test Generator like Pex, OR I could have just used my head and thought of it first. ;) Assert your assumptions. I didn't, and I assumed, wrongy, UserAgent would be non-null.