Checking Success or Failure

How to find out if the operation succeded or failed

As we discovered earlier, we can easily determine if a given Result instance is successful or not.

Checking Success

We can use Result::hasSuccess to obtain a boolean value that represents whether a result is successful.

@Test
void testHasSuccess() {
  // Given
  Result<?, ?> result1 = success(1024);
  Result<?, ?> result2 = failure(1024);
  // When
  boolean result1HasSuccess = result1.hasSuccess();
  boolean result2HasSuccess = result2.hasSuccess();
  // Then
  assertTrue(result1HasSuccess);
  assertFalse(result2HasSuccess);
}

Checking Failure

We can also use Result::hasFailure to find out if a result contains a failure value.

@Test
void testHasFailure() {
  // Given
  Result<?, ?> result1 = success(512);
  Result<?, ?> result2 = failure(512);
  // When
  boolean result1HasFailure = result1.hasFailure();
  boolean result2HasFailure = result2.hasFailure();
  // Then
  assertFalse(result1HasFailure);
  assertTrue(result2HasFailure);
}

Conclusion

We discussed how to determine the state of a Result object using hasSuccess and hasFailure. These methods provide a straightforward way to identify the outcome of an operation, helping you make decisions based on the outcome.

Last updated

Logo

Copyright 2024 Guillermo Calvo