Java modern design patterns
Around Method Pattern
The try-with-resource
feature is useful but it’s quite easy to forget to wrap the resource as the compiler won’t tell you forgot to do it.
One solution is to use the Around Method Pattern
:
Instead of:
public class MyResource implements AutoCloseable {
public void op() {
// do something
}
@Override
public void close() {
// close resource
}
public static void main(String[] args) {
// easy to forget, as the compiler won't yell at you for forgetting
// to wrap your `AutoCloseable`
try (MyResource myResource = new MyResource()) {
myResource.op();
}
}
}
We can do:
public class MyResource {
public static void use(Consumer<MyResource> consumer) {
var myResource = new MyResource();
try {
consumer.accept(myResource);
} finally {
myResource.close();
}
}
public void op() {
// do something
}
private void close() {
// close resource
}
public static void main(String[] args) {
// API consumer don't need to remember to close the resource
MyResource.use(myResource -> myResource.op());
}
}