Skip to content

Commit

Permalink
Refactored to lazy mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
Hakky54 committed Nov 10, 2024
1 parent 7251d2e commit 6cf7a62
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ public SSLEngine getSSLEngine(String peerHost, Integer peerPort) {
* source in a functional way.
*/
public <T> Box<T> map(Function<SSLFactory, T> mapper) {
return new Box<>(this).map(mapper);
return Box.of(this).map(mapper);
}

public static Builder builder() {
Expand Down
47 changes: 34 additions & 13 deletions sslcontext-kickstart/src/main/java/nl/altindag/ssl/util/Box.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,48 @@

import nl.altindag.ssl.exception.GenericException;

import java.util.function.Supplier;

/**
* @author Hakan Altindag
*/
public final class Box<T> {
@FunctionalInterface
public interface Box<T> {

private final T value;
ValueHolder<T> container();

public Box(T value) {
this.value = value;
static <T> Box<T> of(T value) {
return () -> ValueHolder.wrap(() -> value);
}

public <U> Box<U> map(Function<? super T, ? extends U> mapper) {
try {
return new Box<>(mapper.apply(value));
} catch (Exception e) {
throw new GenericException(e);
}
default <R> Box<R> map(Function<? super T, ? extends R> mapper) {
return () -> ValueHolder.wrap(() -> {
final T value = container().get();

try {
return mapper.apply(value);
} catch (Exception e) {
throw new GenericException(e);
}
});
}

default T get() {
return container().get();
}

public T get() {
return value;
@FunctionalInterface
interface ValueHolder<T> {

Supplier<T> valueSupplier();

default T get() {
return valueSupplier().get();
}

static <U> ValueHolder<U> wrap(Supplier<U> supplier) {
return () -> supplier;
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ class BoxShould {

@Test
void wrapAnyExceptionInGenericException() {
Box<String> stringBox = new Box<>("");
assertThatThrownBy(() -> stringBox.map(value -> {
throw new RuntimeException("KABOOM");
}))
Box<String> stringBox = Box.of("")
.map(value -> {
throw new RuntimeException("KABOOM");
});

assertThatThrownBy(stringBox::get)
.isInstanceOf(GenericException.class)
.hasRootCauseMessage("KABOOM");
}
Expand Down

0 comments on commit 6cf7a62

Please sign in to comment.