Java – Is passing an object type as a method parameter always a sign of a bad design?

Is passing an object type as a method parameter always a sign of a bad design?… here is a solution to the problem.

Is passing an object type as a method parameter always a sign of a bad design?

Let’s say I have the following enumeration

public enum EmailType {
    FORGET_PASSWORD, ACHIEVMENT_UNLOCK, WELCOME
}

I have a function that generates email subjects based on type (but it still needs dynamic data), eg

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 is a good design to deal with this? Maybe there is a separate method for each EmailType, but this can lead to a lot of methods, and the topic is not focused when I need to change them.

Solution

You can 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.

Related Problems and Solutions