An assortment of guard and defusing functions which can be used to respectively guard your logic against null values and transform potentially throwing operations into non-throwing ones.
Say you have a method that could potentially throw an exception, and in that case you would want to return either null or a default value, then this package would provide you with that functionality. The API is quite self-explanatory. Here is a little example, however.
Note: this library uses Exceptions as a flow of control mechanism, which is an anti-pattern. It must therefor be a conscious choice to choose this library over, let's say, Optionals.
Get this dependency with the latest version
<dependency>
<artifactId>bouncer</artifactId>
<groupId>com.compilit</groupId>
</dependency>
class ExampleClass {
private final String value;
public Integer getValueAsAInteger() {
return Guards.orNull(() -> Integer.parseInt(value)); //returns null when applying the parseInt functions throws an exception
}
public Integer getValueAsAIntegerOrDefault() {
return Guards.orDefault(
() -> Integer.parseInt(value),
-1
); //returns -1 when applying the parseInt functions throws an exception
}
}
Because checked exceptions need to be actively handled, you'll discover you cannot easily use the normal Supplier/Function/Runnable interfaces, since you are forced to add try/catch arround the logic. To overcome this, I've added an inner class called "Checked" to the Difusers class. Each function in there will accept a ThrowingFunction, ThrowingSupplier and ThrowingRunnable instead of a regular Function, Supplier or Runnable. This way, the potential checked exception will be handled inside the Bouncer library and all other functionality remains the same.