Skip to content

A small package containing several guard clauses that can return default values instead of throwing exceptions

License

Notifications You must be signed in to change notification settings

compilit/bouncer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Bouncer

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.

Installation

Get this dependency with the latest version

<dependency>
  <artifactId>bouncer</artifactId>
  <groupId>com.compilit</groupId>
</dependency>

Usage

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
  }

}

Working with checked exceptions.

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.

About

A small package containing several guard clauses that can return default values instead of throwing exceptions

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages