In a recent discussion, a friend and I have disagreed over the following use of lambda functions to define class functionality. When creating an object with dynamic values, should the dynamic values be passed using lambdas, or provided using overriden methods in a custom subclass?
Consider the following example, in which the goal is to have a custom label component with dynamic text and icon traits. This label must have methods getText()
and getIcon()
. Following are two examples: one using multiple lambdas, and one defining a subclass.
Lambda approach:
class Label {
private Supplier<String> text;
private Supplier<Image> icon;
public Label(Supplier<String> text, Supplier<Image> icon) {
this.text = text;
this.icon = icon;
}
public String getText() {
return text.get();
}
public Image getIcon() {
return icon.get();
}
}
Use:
Label timeLabel = new Label(
() -> System.currentTimeMillis(),
() -> CLOCK_IMAGE
);
Subclass approach:
class Label {
private String text;
private Image icon;
public Label() {
// some default
}
public Label(String text, Image icon) {
// set fields
}
// simple getters
}
Use:
class TimeLabel extends Label {
public String getText() {
return System.currentTimeMillis();
}
public Image getImage() {
return CLOCK_IMAGE;
}
}
Label timeLabel = new TimeLabel();
Which of these approaches is more appropriate, considering expectations, readability, and usability for both internal and external developers (including as a class for an API)?