|
| 1 | +# algebra |
| 2 | +Generic ADTs in Java. |
| 3 | + |
| 4 | +## Using |
| 5 | + |
| 6 | +To use `algebra` in your project simply include it in your POM: |
| 7 | + |
| 8 | +```xml |
| 9 | + <dependency> |
| 10 | + <groupId>com.hubspot</groupId> |
| 11 | + <artifactId>algebra-public</artifactId> |
| 12 | + <version>1.0</version> |
| 13 | + </dependency> |
| 14 | +``` |
| 15 | + |
| 16 | +## Provided Types |
| 17 | + |
| 18 | +The main type provided by `algebra` is the `Result<T, E>`. `T` and `E` can be any classes you want, but it is generally advisable that `E` be an enum or another ADT so you can correctly match on error conditions. Lets take a look at an example. |
| 19 | + |
| 20 | +```java |
| 21 | +enum Error { |
| 22 | + BROKEN, |
| 23 | + REALLY_BROKEN |
| 24 | +} |
| 25 | + |
| 26 | +public Result<String, Error> doWork() { |
| 27 | + if (sucess) { |
| 28 | + return Result.ok(result); |
| 29 | + } else if (thing1Broke) { |
| 30 | + return Result.err(Error.BROKEN); |
| 31 | + } |
| 32 | + |
| 33 | + return Result.err(Error.REALLY_BROKEN); |
| 34 | +} |
| 35 | +``` |
| 36 | + |
| 37 | +If we then want to use `doWork` in a library, but our library only has one error type, we can simply map the error and return a new result: |
| 38 | + |
| 39 | +```java |
| 40 | + |
| 41 | +enum LibError { |
| 42 | + ERROR |
| 43 | +} |
| 44 | + |
| 45 | +public Result<String, LibError> doMoreWork() { |
| 46 | + return doWork().mapErr(err -> LibError.ERROR); |
| 47 | +} |
| 48 | +``` |
| 49 | + |
| 50 | +Of course when it gets to our client and they actually want to handle the error they can do so using `match`: |
| 51 | + |
| 52 | +```java |
| 53 | +client.doMoreWork().match( |
| 54 | + err -> LOGGER.error("Got error: {}", err), |
| 55 | + ok -> LOGGER.info("Got successful result: {}", ok) |
| 56 | +); |
| 57 | +``` |
| 58 | + |
| 59 | +## Testing |
| 60 | + |
| 61 | +To test code with ADTs, we provide a fluent AssertJ API in `algebra-public-testing`. |
| 62 | + |
| 63 | +To use `algebra-public-testing` in your project simply include it in your POM: |
| 64 | + |
| 65 | +```xml |
| 66 | + <dependency> |
| 67 | + <groupId>com.hubspot</groupId> |
| 68 | + <artifactId>algebra--public-testing</artifactId> |
| 69 | + <version>1.0</version> |
| 70 | + <scope>test</scope> |
| 71 | + </dependency> |
| 72 | +``` |
| 73 | + |
| 74 | +Add a static import and use the assertions: |
| 75 | + |
| 76 | +```java |
| 77 | +import static com.hubspot.assertj.algebra.api.Assertions.assertThat; |
| 78 | +import static org.assertj.core.api.Assertions.assertThat; |
| 79 | +``` |
| 80 | + |
| 81 | +```java |
| 82 | + @Test |
| 83 | + public void itWorks() { |
| 84 | + assertThat(Result.ok("Ok")) |
| 85 | + .isOk() |
| 86 | + .containsOk("Ok"); |
| 87 | + } |
| 88 | +``` |
0 commit comments