Methods of simplifying ugly nested if-else trees in C#

前端 未结 11 810
野性不改
野性不改 2021-02-02 04:23

Sometimes I\'m writing ugly if-else statements in C# 3.5; I\'m aware of some different approaches to simplifying that with table-driven development, class hierarchy, anonimous m

11条回答
  •  旧巷少年郎
    2021-02-02 04:40

    Good question. "Conditional Complexity" is a code smell. Polymorphism is your friend.

    Conditional logic is innocent in its infancy, when it’s simple to understand and contained within a few lines of code. Unfortunately, it rarely ages well. You implement several new features and suddenly your conditional logic becomes complicated and expansive. [Joshua Kerevsky: Refactoring to Patterns]

    One of the simplest things you can do to avoid nested if blocks is to learn to use Guard Clauses.

    double getPayAmount() {
    if (_isDead) return deadAmount();
    if (_isSeparated) return separatedAmount();
    if (_isRetired) return retiredAmount();
    return normalPayAmount();
    };  
    

    The other thing I have found simplifies things pretty well, and which makes your code self-documenting, is Consolidating conditionals.

    double disabilityAmount() {
        if (isNotEligableForDisability()) return 0;
        // compute the disability amount
    

    Other valuable refactoring techniques associated with conditional expressions include Decompose Conditional, Replace Conditional with Visitor, Specification Pattern, and Reverse Conditional.

提交回复
热议问题