Using extenders to abstract details and improve code readability
2 min read
2 min read
if(someObject.stringPropertyX.Equals("abc") || someObject.stringPropertyX.Equals("def") || ....){This concatenated or's or also ands may be quite messy to look at and also to change. And in addition it's not very comfortable to write since you repeatedly have to write the object.property etc...(or copy&paste it). Packing all of this inside an extender method for the string object (this is just a special case, you could do that of course also for other kind of objects) makes everything much cleaner:
//do something
...
}else{
//do something other...
....
}
using System;So using the extender with the dummy example above would result in the following code
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Some.Namespace.Extenders
{
public static class StringExtender
{
/// <summary>
/// Evaluates whether the String is contained in AT LEAST one of the passed values (i.e. similar to the "in" SQL clause)
/// </summary>
/// <param name="thisString"></param>
/// <param name="values">list of strings used for comparison</param>
/// <returns><c>true</c> if the string is contained in AT LEAST one of the passed values</returns>
public static bool In(this String thisString, params string[] values)
{
foreach (string val in values)
{
if (thisString.Equals(val, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false; //no occurence found
}
}
}
if(someObject.stringPropertyX.In("abc", "def",...,"xyz"){Doesn't this look much nicer?? I find it much more readable. It abstracts and hides all of the logical operators and property calls. By looking at the code you immediately see the important facts without being distracted. You're also much quicker in adding (in this case) new strings for comparison in contrast to the case before where you have to make sure to copy (write) the object + parameter invocation, add the logical connector properly etc... You could easily do the same with the AND logical operator and also for the corresponding negations (I just didn't work out the details).
//do something
...
}else{
//do something other...
....
}