https://github.com/hubspot/algebra
Simple abstract data types (wrapping derive4j) in Java
https://github.com/hubspot/algebra
Last synced: 6 months ago
JSON representation
Simple abstract data types (wrapping derive4j) in Java
- Host: GitHub
- URL: https://github.com/hubspot/algebra
- Owner: HubSpot
- License: apache-2.0
- Created: 2018-03-14T00:45:00.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2025-08-11T17:57:35.000Z (11 months ago)
- Last Synced: 2025-08-11T19:26:24.237Z (11 months ago)
- Language: Java
- Homepage:
- Size: 163 KB
- Stars: 18
- Watchers: 154
- Forks: 7
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# algebra
Generic ADTs in Java.
## Using
To use `algebra` in your project simply include it in your POM:
```xml
com.hubspot
algebra
1.2
```
## Provided Types
The main type provided by `algebra` is the `Result`. `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.
```java
enum Error {
BROKEN,
REALLY_BROKEN
}
public Result doWork() {
if (success) {
return Result.ok(result);
} else if (thing1Broke) {
return Result.err(Error.BROKEN);
}
return Result.err(Error.REALLY_BROKEN);
}
```
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:
```java
enum LibError {
ERROR
}
public Result doMoreWork() {
return doWork().mapErr(err -> LibError.ERROR);
}
```
Of course when it gets to our client and they actually want to handle the error they can do so using `match`:
```java
client.doMoreWork().match(
err -> LOGGER.error("Got error: {}", err),
ok -> LOGGER.info("Got successful result: {}", ok)
);
```
## Testing
To test code with ADTs, we provide a fluent AssertJ API in `algebra-testing`.
To use `algebra-testing` in your project simply include it in your POM:
```xml
com.hubspot
algebra-testing
1.2
test
```
Add a static import and use the assertions:
```java
import static com.hubspot.assertj.algebra.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
```
```java
@Test
public void itWorks() {
assertThat(Result.ok("Ok"))
.isOk()
.containsOk("Ok");
}
```