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

前端 未结 11 801
野性不改
野性不改 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:38

    There are very old "formalisms" for trying to encapsulate extremely complex expressions that evaluate many possibly independent variables, for example, "decision tables" :

    http://en.wikipedia.org/wiki/Decision_table

    But, I'll join in the choir here to second the ideas mentioned of judicious use of the ternary operator if possible, identifying the most unlikely conditions which if met allow you to terminate the rest of the evaluation by excluding them first, and add ... the reverse of that ... trying to factor out the most probable conditions and states that can allow you to proceed without testing of the "fringe" cases.

    The suggestion by Miriam (above) is fascinating, even elegant, as "conceptual art;" and I am actually going to try it out, trying to "bracket" my suspicion that it will lead to code that is harder to maintain.

    My pragmatic side says there is no "one size fits all" answer here in the absence of a pretty specific code example, and complete description of the conditions and their interactions.

    I'm a fan of "flag setting" : meaning anytime my application goes into some less common "mode" or "state" I set a boolean flag (which might even be static for the class) : for me that simplifies writing complex if/then else evaluations later on.

    best, Bill

提交回复
热议问题