處理特殊情況的擴充套件方法

擴充套件方法可用於隱藏處理不優雅的業務規則,否則這些規則將需要使用 if / then 語句來混淆呼叫函式。這與使用擴充套件方法處理空值類似且類似。例如,

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.