Skip to content

Instantly share code, notes, and snippets.

@kijanowski
Last active November 4, 2018 19:16
Show Gist options
  • Select an option

  • Save kijanowski/213e420ee5cd78c06ee74a13040f7671 to your computer and use it in GitHub Desktop.

Select an option

Save kijanowski/213e420ee5cd78c06ee74a13040f7671 to your computer and use it in GitHub Desktop.
nestedConditionWithMultipleValues
// instead of
public void legacyNestedConditionWithMultipleValues(String nullableValueA, String nullableValueB) {
if (nullableValueA == null && nullableValueB == null) {
exec.methodOne(DEFAULT);
} else if (nullableValueA == null) { // nullableValueB != null
exec.methodOne(nullableValueB);
} else if (nullableValueB == null) { // nullableValueA != null
exec.methodTwo(nullableValueA);
} else { // nullableValueA != null && nullableValueB != null
exec.methodThree(DEFAULT);
}
}
// do it the functional way
public void vavrNestedConditionWithMultipleValues(String nullableValueA, String nullableValueB) {
Match(new Tuple2<>(Option.of(nullableValueA), Option.of(nullableValueB))).of(
Case($Tuple2($None(), $None()), () -> run(() -> exec.methodOne(DEFAULT))),
Case($Tuple2($None(), $Some($())), () -> run(() -> exec.methodOne(nullableValueB))),
Case($Tuple2($Some($()), $None()), () -> run(() -> exec.methodTwo(nullableValueA))),
Case($Tuple2($Some($()), $Some($())), () -> run(() -> exec.methodThree(DEFAULT)))
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment