Extension methods for handling special cases

suggest change

An 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents