Skip to content

Commit ce79cbd

Browse files
authored
Add execute around method pattern (#38)
1 parent f736ff8 commit ce79cbd

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package pl.mperor.lab.java.design.pattern.behavioral.eam;
2+
3+
import java.util.function.Supplier;
4+
5+
public class Retry {
6+
7+
private final int retries;
8+
9+
private Retry(int retries) {
10+
this.retries = retries;
11+
}
12+
13+
public <T> T retry(Supplier<T> action) {
14+
Exception lastException = null;
15+
16+
for (int i = 0; i < retries; i++) {
17+
try {
18+
return action.get();
19+
} catch (Exception e) {
20+
lastException = e;
21+
}
22+
}
23+
24+
throw new NoRetriesRemainException("Failed to execute action after %s attempts".formatted(retries), lastException);
25+
}
26+
27+
public static Retry of(int retries) {
28+
return new Retry(retries);
29+
}
30+
31+
public static class NoRetriesRemainException extends RuntimeException {
32+
public NoRetriesRemainException(String message, Throwable cause) {
33+
super(message, cause);
34+
}
35+
}
36+
37+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package pl.mperor.lab.java.design.pattern.behavioral.eam;
2+
3+
import org.junit.jupiter.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
import pl.mperor.lab.common.TestUtils;
6+
7+
import java.util.List;
8+
import java.util.stream.IntStream;
9+
10+
public class ExecuteAroundMethodTest {
11+
12+
@Test
13+
public void shouldAllowToUseExecuteAroundMethod() {
14+
var out = TestUtils.setTempSystemOut();
15+
executeAround(() -> System.out.println("action"));
16+
Assertions.assertLinesMatch(List.of("setup", "action", "tear down"), out.lines());
17+
TestUtils.resetSystemOut();
18+
}
19+
20+
private static void executeAround(Runnable action) {
21+
System.out.println("setup");
22+
action.run();
23+
System.out.println("tear down");
24+
}
25+
26+
@Test
27+
public void testRetry() {
28+
var exception = Assertions.assertThrows(Retry.NoRetriesRemainException.class, () -> Retry.of(3).retry(() -> 1 / 0));
29+
Assertions.assertInstanceOf(ArithmeticException.class, exception.getCause());
30+
Assertions.assertEquals(10, Retry.of(1).retry(() -> IntStream.rangeClosed(1, 4).sum()));
31+
}
32+
33+
}

0 commit comments

Comments
 (0)