Extension methods for handling special cases
suggest changeExtension methods can be used to “hide” processing of inelegant business rules that would otherwise require cluttering up a calling function with if/then statements. This is similar to and analogous to handling nulls with extension methods. For example,
public static class CakeExtensions
{
public static Cake EnsureTrueCake(this Cake cake)
{
// If the cake is a lie, substitute a cake from grandma, whose cakes aren't as tasty but are known never to be lies. If the cake isn't a lie, don't do anything and return it.
return CakeVerificationService.IsCakeLie(cake) ? GrandmasKitchen.Get1950sCake() : cake;
}
}
Cake myCake = Bakery.GetNextCake().EnsureTrueCake();
myMouth.Eat(myCake);//Eat the cake, confident that it is not a lie.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents