Some times I have texts 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 will have the same phrases (here This exception throws under situation1
):
/**
* This exception throws under situation1 ...
*
*/
public class SomeException extends Exception {
public static class Builder{
String message = "This exception throws under situation1. So ... ";
public Builder(String message) {
this.message = this.message + "\r\n" + message;
}
public SomeException build(){
return new SomeException(this);
}
}
private SomeException(String detailMessage) {
super(detailMessage);
}
public SomeException(Builder builder) {
this(builder.message);
}
}
And also documents of each method that throw exception will have the same phrase:
/**
* @throws SomeException
* This exception throws under situation1 ...
*/
private void test() throws SomeException {
throw new SomeException.Builder("message").build();
}
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
/**
* exception throws under situation1
*/
public static final String CONSTANT = "exception throws under situation1";
and reference to it (and it's comment):
/**
* {@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 {
/**
* exception throws under situation1
*/
CONSTANT("exception throws under situation1");
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.
Meta.CONSTANT.getText()
? Where would you be using that?