Format enum variables when they are called

John R. :

Is there any way to format the enum variables when they are called? I mean, If I have the next enum:

public enum Error{
IS_NULL("The variable {NAME_OF_VARIABLE} cannot be null.")
}

So, when I call it I want to replace {NAME_OF_VARIABLE} with the variable which is null. Ex: "The variable {phone_number} is null."

Now I use the next construction:

 enum Error{ 

    IS_NULL("The variable {%s} cannot be null.")

    public String errorMsg;
    }

    public String validatePhoneNumber(String phoneNumber){
    if(phoneNumber == null){
    return String.format(Error.IS_NULL.errorMsg, "phoneNumber")}
    return "OK"}
    }
}

It works fine, but it looks a bit messy.

Thank you!

Nicholas K :

Firstly your code doesn't compile and you can make use of a ternary operator to check if the phoneNumber is null or not.

Given the enum :

enum Error {

    IS_NULL("The variable {%s} cannot be null.");

    public String errorMsg;

    private Error(String errorMsg) {
        this.errorMsg = errorMsg;
    }

}

Validation method can be simplified to

public static String validatePhoneNumber(String phoneNumber) {
  return phoneNumber == null ? String.format(Error.IS_NULL.errorMsg, "phoneNumber") : "OK";
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130614&siteId=1