Extension methods for handling special cases
suggest changeAn extension method can hide an awkward business rule that would otherwise clutter the caller with if statements. This is the same idea as a null-checking extension. 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