I'm sure most developers will agree when I say that one of the characteristics of good code is readability. Those of who've had the misfortune to decipher someone else's code can attest to that. I've found myself in that situation plenty of times. At first I thought it was the norm-short cryptic names to keep things simple, complicated algorithms to make it look cool (and show off what our extensive knowledge).
But recently I've been shown the light. The lead developer at the company I work for, DMiPartners, convinced me about the importance of readable code. The argument for which is beyond the scope of this article, maybe in the future I'll expand on it.
What I want to share was my eureka moment and how it came about. I've always been a fan of extension methods but it wasn't until now that I was able to really experiment with them. It started with piece of code that I always found unreadable and at times confusing:
if(!String.IsNullOrEmpty(myStringVar){ //do something cool }
The code is read literally like this: If not string dot is null or empty, myStringVar, then do something. I've always felt as if it read like some form of developer dialect of english so I was never comfortable using it. The IsNullOrEmpty method, provided by the string object in .Net is very useful but I always figured it be easier read as an extension method like this:
if(myStringVar.IsNullOrEmpty()){ //do something cool }
Now it reads: if myStringVar is null or empty, do something. If it were VB it would be even more readable given the keyword Then before running any code. So I wrote the extension method and placed it under the root namespace of my project to make it globally available. Then I was in a situation where I had to negate the boolean returned from my new extension method but I didn't want to do this:
if(!myStringVar.IsNullOrEmpty()) { //do something }
That would obviously destroy the usability of the extension method. So I created another one:
if(myStringVar.IsNotNullOrEmpty()){ //do something }
I used both of them several times and when I read my code I realized how quickly I was able to understand what my code was doing. Instead of trying to figure out what the NOT operator (!) was trying to tell me I understood my code without giving it a second thought. That was my eureka moment.
The code is painfully obvious:
public bool IsNotNullOrEmpty(this string varToCheck){
return !String.IsNullOrEmpty(varToCheck);
}
Some may argue that its not necessary to go through the trouble to write an extension method for such a simple line of code, but I'd disagree. The benefit can be seen in increased productivity given that a developer would spend less time trying to decrypt another developer's code when a change has to be made.