I have this scenario
abstract class Notification<C extends Config> {
private String text;
private String title;
private String topic;
private C configuration;
public C getConfig() {
return configuration;
}
public void setConfig(C configuration) {
this.configuration = configuration;
}
public String getText() {return text;}
public void setText(String text) {this.text = text;}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
}
class NotificationA extends Notification<ConfigA> {
private Boolean notificationAccepted;
public Boolean getNotificationAccepted() {
return notificationAccepted;
}
public void setNotificationAccepted(Boolean notificationAccepted) {
this.notificationAccepted = notificationAccepted;
}
}
class NotificationB extends Notification<ConfigB> {
private LocalDate expirationDate;
public LocalDate getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(LocalDate expirationDate) {
this.expirationDate = expirationDate;
}
}
class NotificationC extends Notification<ConfigC> {
private Boolean resend;
public boolean resend() {return this.resend;}
public void setResend(Boolean resend) {
this.resend = resend;
}
public LocalDate getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(LocalDate expirationDate) {
this.expirationDate = expirationDate;
}
}
But this is causing me issues because I have to create Notifications depending on the Configuration I have, like this:
public Notification createNotification(Configuration configuration) {
if(configuration instanceof ConfigurationA) {
return new NotificationA();
} else if (configuration instanceof ConfigurationB) {
//...
}
}
But then if I try to do this:
Notification notification = createNotification(configuration);
notification.setConfig(configuration); //Unchecked call to setConfig()!
As you can see, everything sucks here because I have to cast Notification again so the compiler does not complain about that unchecked call.
Can anyone please provide a better solution? I feel I have no way to fix this bad design.
If inheritance is not a good idea here then what should I do not to repeat code?
If this is not clear enough please kindly tell me what to fix in a comment. This is my first post on SO.