How can I refactor out the required else clause?

后端 未结 6 464
春和景丽
春和景丽 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条回答
  •  Happy的楠姐
    2021-01-12 09:55

    You could make your code into a kind of truth table, which depending on your real-world case might make it more explicit:

    let condA() = true
    let condB() = false
    let condC() = true
    
    let doThingA() = Console.WriteLine("Did work A")
    let doThingB() = Console.WriteLine("Did work B")
    let doThingC() = Console.WriteLine("Did work C")
    
    let Eval() : bool =
        match condA(), condB(), condC() with
        | true,  false, _     -> doThingA();                           false;
        | true,  true,  false -> doThingA(); doThingB();               false;
        | true,  true,  true  -> doThingA(); doThingB(); doThingC();   true;
        | false, _,     _     ->                                       false;
    

提交回复
热议问题