prettyvoid :
Assume I have the following enum
public enum EmailType {
FORGET_PASSWORD, ACHIEVMENT_UNLOCK, WELCOME
}
and I have a function that generates email subjects based on the type (but it still requires dynamic data), e.g.
public String generateEmailSubject(EmailType emailType, Object obj) {
String subject;
switch(emailType) {
case WELCOME:
User user = (User) obj;
subject = "Hello " + user.getFirstName();
case FORGET_PASSWORD:
User user = (User) obj;
subject = "Forget password " + user.getEmail();
break;
case ACHIEVMENT_UNLOCK:
Achievment achievment = (Achievment) obj;
subject = "Achievment Unlock:" + achievment.getTitle();
break;
}
return subject;
}
Is this bad practice? If so, what's a good design to handle this? Maybe a separate method for each EmailType
but that could lead to a lot of methods and the subjects will not be centralized when I need to change them.
khelwood :
You could use polymorphism for this.
interface Subjectable {
String getSubject();
}
class Achievement implements Subjectable {
...
@Override
public String getSubject() {
return "Achievement unlocked: " + getTitle();
}
}
class User implements Subjectable {
...
@Override
public String getSubject() {
return "Forgot password: " + getEmail();
}
}
Then you don't need to explicitly check the type of the object: you just call getSubject()
on it.