githubEdit

Screening Results

How to reject success values and accept failure values

circle-info

Screening mechanisms provide greater flexibility in handling edge cases and enable more robust error recovery strategies.

The following methods allow you to run inline tests on the wrapped value of a result to dynamically transform a success into a failure or a failure into a success.

Validating Success

The Result::filterarrow-up-right method allows you to transform a success into a failure based on certain conditions. It takes two parameters:

  1. A Predicatearrow-up-right to determine if the success value is acceptable.

  2. A mapping Functionarrow-up-right that will produce a failure value if the value is deemed unacceptable.

circle-check
@Test
void testFilter() {
  // Given
  Result<Integer, String> result = success(1);
  // When
  Result<Integer, String> filtered = result.filter(x -> x % 2 == 0, x -> "It's odd");
  // Then
  assertTrue(filtered.hasFailure());
}

In this example, we use a lambda expression to validate that the success value inside result is even. Since the number is odd, it transforms the result into a failure.

triangle-exclamation

Recovering From Failure

The Result::recoverarrow-up-right method allows you to transform a failure into a success based on certain conditions. It also receives two parameters:

  1. A Predicatearrow-up-right to determine if the failure value is recoverable.

  2. A mapping Functionarrow-up-right that will produce a success value from the acceptable failure value.

circle-check

In this example, we use method references to check if the failure value equals OK and then transform the result into a success.

Conclusion

We covered how to filter out unwanted success values and accept failure values using filterarrow-up-right and recoverarrow-up-right. These methods enable you to refine results based on specific criteria, ensuring that only the relevant values are processed down the line.

Last updated

Was this helpful?