rewrite-static-analysis icon indicating copy to clipboard operation
rewrite-static-analysis copied to clipboard

Extend TernaryOperatorsShouldNotBeNested with pattern matching

Open pstreef opened this issue 1 year ago • 0 comments

What problem are you trying to solve?

Pattern matching switch expressions can be used to simplify nested ternaries

Describe the solution you'd like

"""
  import java.util.Set;
  import java.util.Arrays;
  import java.util.List;
  import java.util.stream.Collectors;
  class Test {
    public Set<String> makeASet() {
       List<String> s = Arrays.asList("a","b","c","nope");
       return s.stream().map(item -> item.startsWith("a") ? "a" : item.startsWith("b") ? "b" : "nope").collect(Collectors.toSet());
    }
  }
  """,
"""
  import java.util.Set;
  import java.util.Arrays;
  import java.util.List;
  import java.util.stream.Collectors;
  class Test {
    public Set<String> makeASet() {
       List<String> s = Arrays.asList("a","b","c","nope");
       return s.stream().map(item ->
        switch (item) {
          case String st && st.startsWith("a") -> "a";
          case String st && st.startsWith("b") -> "b";
          default -> "nope";
        }
       ).collect(Collectors.toSet());
    }
  }
  """

pstreef avatar Aug 22 '23 18:08 pstreef