Other ways to deal with “loop initialization” in C#

前端 未结 9 785
陌清茗
陌清茗 2020-12-24 07:22

To start with I\'ll say that I agree that goto statements are largely made irrelevant by higher level constructs in modern programming languages and shouldn\'t be used when

9条回答
  •  眼角桃花
    2020-12-24 08:11

    There are ways you "can" get around the doubled code, but in most cases the duplicated code is much less ugly/dangerous than the possible solutions. The "goto" solution you quote doesn't seem like an improvement to me - I don't really think you really gain anything significant (compactness, readability or efficiency) by using it, while you increase the risk of a programmer getting something wrong at some point in the code's lifetime.

    In general I tend to go for the approach:

    • A special case for the first (or last) action
    • loop for the other actions.

    This removes the inefficiencies introduced by checking if the loop is in the first iteration on every time around, and is really easy to understand. For non-trivial cases, using a delegate or helper method to apply the action can minimise code duplication.

    Or another approach I use sometimes where efficiency isn't important:

    • loop, and test if the string is empty to determine if a delimiter is required.

    This can be written to be more compact and readable than the goto approach, and doesn't require any extra variables/storage/tests to detect the "special case" iteraiton.

    But I think Mark Byers' approach is a good clean solution for your particular example.

提交回复
热议问题