Skip to main content
2 of 10
edited body
user avatar
user avatar

Way to organize repetitive text in Java

Usually I have text that appears in different places, like comments, messages... For example if I have a custom Exception, probably class doc, messages that passes as parameter to its constructor and documents of each method that throw exception will have the same phrases and terms. If I copy/paste phrase, maintenance of documents will be hard (it needs finding and updating all repeats on each edit).

To solve this, I can use a constant string that its value and its comment are those repetitive terms

/**
 * comment for CONSTANT
 */
public static final String CONSTANT = "comment for CONSTANT";

and reference to it:

    /**
     * {@link MyClass#CONSTANT}
     */
    String message = MyClass.CONSTANT;

But how organize constants when are more than one? With respect to this answer and this one, it seems the best way to organize them is using enum:

public enum Meta {
    /**
    * comment for CONSTANT
    */
    CONSTANT("comment for CONSTANT");
    
    private String text;

    Meta(String text) {
        this.text = text;
    }

    public String getText() {
        return this.text;
    }

}

But is there a better way than this? Especially it complicates code.

hasanghaforian
  • 651
  • 1
  • 6
  • 14