Reputation: 92384
I've ended up with a couple of methods in several classes that follow the same patterns (it's always a bunch of those methods within each class):
private void updateFoo() {
String newFoo = fooTextField.getText();
if (!newFoo.equals(record.getFoo())) {
// "record" stays the same for all methods of this pattern.
record.setFoo(newFoo);
record = DATABASE.save(record);
}
}
I can't seem to make this generic as there doesn't seem to be a way to pass a reference to a variable, like void f(int *outFoo) { *outFoo = 42; }
in C.
Ideally, I'd like to have something like:
private void update(JTextField textField, ? getter, ? setter) {
String newFoo = textField.getText();
if (!newFoo.equals(getter())) {
// "record" stays the same for all methods of this pattern.
setter(newFoo);
record = DATABASE.save(record);
}
}
so that in the end, I can do something like (pseudo-code):
update(fooTextField, &record.getFoo, &record.setFoo);
Given the lack of closures in Java, the next best thing I can think of is an interface that "maps" the necessary method calls but this tends to need even more text to type than simply copying those methods. Is there an elegant way to solve this?
Upvotes: 0
Views: 155
Reputation: 41208
As mentioned in the comments closures in Java 8 will help here.
Something that can be done with current Java is to pass in String objects for the method names, using reflection to call the methods and then return the newFoo. There is a better way though which involves no generics and no reflection:
String update(JTextField textField, String oldFoo) {
String newFoo = textField.getText();
if (!newFoo.equals(oldFoo)) {
record = DATABASE.save(record);
}
return newFoo;
}
Then each time you use the code it just becomes:
setter(update(textField, getter()));
For example:
setName(update(textFieldName, getName()));
Which has removed most of your DRY concerns. The only real drawback is the fact that the setter gets called even on no change, I'd expect the setter to be pretty lightweight though so that shouldn't be an issue.
Upvotes: 1