How can I refactor out the required else clause?

后端 未结 6 442
春和景丽
春和景丽 2021-01-12 09:13

I have a C# method that looks a bit like this:

bool Eval() {
  // do some work
  if (conditionA) {
     // do some work
     if (conditionB) {
       // do s         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 09:49

    As mentioned in the comments, you could inverse the condition. This simplifies the C# code, because you can write:

    if (!conditionA) return false;
    // do some work
    

    Although F# does not have imperative returns (if you want to return, you need both true and false branches), it actually simplifies this code a bit too, because you can write:

    let eval() = 
      // do some work 
      if not conditionA then false else
      // do some work 
      if not conditionB then false else
      // do some work 
      if not conditionC then false else
        // do some work 
        true 
    

    You still have to write false multiple times, but at least you don't have to indent your code too far. There is an unlimited number of complex solutions, but this is probably the simplest option. As for more complex solution, you could use an F# computation expression that allows using imperative-style returns. This is similar to Daniel's computation, but a bit more powerful.

提交回复
热议问题