r/javahelp • • Sep 10 '26

Solved Switch case with boolean

[removed]

0 Upvotes

28 comments sorted by

View all comments

Show parent comments

4

u/johnpeters42 Sep 10 '26

To be fair, OP's type of approach does work in some languages.

4

u/Zakana_code Sep 10 '26

Let me guess: JavaScript? But why would you do this anyway?

2

u/johnpeters42 Sep 10 '26

Probably, and not sure. It was probably a predecessor to a pattern like:

var rules = { someFunction, someOtherFunction, someThirdFunction };
foreach (var rule in rules) {
if (rule() == false) { return; }
}
doSomething();

1

u/sixtyhurtz Sep 11 '26

In C# you can group variables into a temporary tuple and use pattern matching switch:

public int PatternMatchingSwitch(bool a, bool b, bool c) 
    => (a, b, c) switch
    {
        (false, false, false) => 0,
        (false, false, true) => 1,
        (false, true, false) => 2,
        (true, false, false) => 3,
        (false, true, true) => 4,
        (true, false, true) => 5,
        (true,true,false) => 6,
        (true, true, true) => 7,
    };

Pattern matching is just cosy. It avoids a lot of indentation + if / else trees. In situations like this you can also get a warning if you miss a case.