-2
\$\begingroup\$

I have a couple of chemical reactions. One of them is described as "If insulin is mixed with antibiotic, healthy people catch Fever". I think it would be useful for logging to keep these description strings inside the code. I have thought of 2 approaches but they both seem kind of wrong.

Approach 1

public abstract class ChemicalReaction {

    public abstract String getDescription();
}

public class AntibioticInsulinReaction {

    private static final String DESCRIPTION = "If insulin is mixed with antibiotic, healthy people catch Fever";

    public String getDescription(){ return DESCRIPTION; }
}

Instance method returns a static variable.

Approach 2

public final class ChemicalReaction {

    private final String description;

    public ChemicalReaction(final String description){

        this.description = description;
    }

    public String getDescription(){ return description; }
}

public class Main {

    public static void main(String[] args){

        ChemicalReaction antibioticInsulinReaction = new ChemicalReaction("If insulin is mixed with antibiotic, healthy people catch Fever");
    }
}

Magic string.

Do you see any other way to do it? Or maybe I don't need to?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Hard to advise you, without knowing what other functionality needs to be supported by these ChemicalReaction objects. I've voted to close the question for lack of context. \$\endgroup\$ Sep 16, 2018 at 2:57

1 Answer 1

1
\$\begingroup\$

You can use the power of Enum. As oracle says

Consider following example:

enum ChemicalReaction {
    ANTIBIOTIC_INSULIN("If insulin is mixed with antibiotic, healthy people catch Fever");

    private String description;
    ChemicalReaction(String s) {
        this.description = s;
    }

    public String getDescription() {
        return description;
    }
}

public static void main(String[] args) {
    ChemicalReaction reaction = ChemicalReaction.ANTIBIOTIC_INSULIN;

    if (reaction == ChemicalReaction.ANTIBIOTIC_INSULIN) {
        System.out.println("Safe == check");
    }

    switch (reaction) {
        case ANTIBIOTIC_INSULIN:
            System.out.println("Easy switch");
    }

    for (ChemicalReaction chemicalReaction : ChemicalReaction.values()) {
        System.out.println(chemicalReaction.getDescription());
    }
}

Enums support a lot of cool things, like comparing with ==, simple use in switch statements, they can include methods and other fields in class body, have already several helper methods like static .values() method that returns an array containing all of the values of the enum in the order they are declared.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.