I'd like to refactor some UI code.
I have a HTML form (here: written in a Java GUI called Wicket) where I put some links (anchor tags). Instead of repeating the code over and over again, I want to create a new elegant helper method.
String type = "", id = "";
Form form, Service service;
form.add(new Widget("createLink", form) { // the same for read, update, delete
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
try {
service.create(type, id); // the same for service.read / update / delete
info("Specific message for create, read, update, delete");
} catch (DataAccessException e) {
error(ExceptionUtils.getRootCauseMessage(e));
}
}
});
form.add(new Widget("readLink", form) {
// ... service.read(...); info("... read ...");
});
form.add(new Widget("updateLink", form) {
// ... service.update(...); info("... update ...");
});
As you've already guessed, I would like to have sth. like
form.add(createLink(htmlId, form, type, id, message, ?));
I'd like to avoid create an extra class for that. But Lambdas would be fine.
What would be the best approach? And how is the pattern called?
Thanks.
For ?
you can use java.util.function.Consumer
:
private void createLink(String htmlId, Form<?> form, String type, String id, String feedbackMessage, Runnable _onSubmit) {
return new Widget(htmlId, form) {
private static final long serialVersionUID = 1L;
@Override
public void onSubmit() {
try {
_onSubmit();
info(feedbackMessage);
} catch (DataAccessException e) {
error(ExceptionUtils.getRootCauseMessage(e));
}
}
}
}
Usage:
form.add(createLink("createLink", form, type, id, createMessage, () -> {
service.create(type, id);
}));