VirtualLogic
VirtualLogic

Reputation: 746

Defining Constant in Static Nested Class

I am defining constants in Static Nested Class

public final class Constants {

public static final class LDAP {
    public static final String BASE_DN = "dc=example,dc=com";
    public static final String OU = "ou";
    public static final String CN = "cn";
    public static final String SN = "sn";
    public static final String GID_NUMBER = "gidNumber";
    public static final String UID_NUMBER = "uidNumber";
    public static final String HOME_DIRECTORY = "homeDirectory";
    public static final String UID = "uid";
    public static final String TELE_PHONE_NUMBER = "telephoneNumber";
    public static final String USER_PASSWORD = "userPassword";

    public static final String OBJECT_CLASS = "objectclass";
    public static final String OBJECT_CLASS_TOP = "top";
    public static final String OBJECT_CLASS_PERSON = "person";
    public static final String OBJECT_CLASS_POSIX_ACCOUNT = "posixAccount";
}

public static final class GenericStringConstan {
    public static final String EMAIL_REPLACE_CHAR_FROM = "@";
    public static final String EMAIL_REPLACE_CHAR_TO = "__";
    public static final String BACK_SLASH = "/";
    public static final String FORWARD_SLASH = "/";

}

}

Is that a best practice to do so? With this I am trying to grouping all constant in single class.
What are the pros and cons with these approach.
Or It is better do create a separate class for different type of constants?

Upvotes: 0

Views: 2117

Answers (2)

Pablo Lozano
Pablo Lozano

Reputation: 10342

I don't like this approach because your class Constants becomes nothing else that part of the package path:

my.package.path.Constants.LDAP.UID

and still it's difficult to find any constant because the file can be huge. I'd create a different file for each group of constants/enums.

Upvotes: 1

Jakub H
Jakub H

Reputation: 2158

If your constants are strictly connected with enclosing class you can have them inside nested class. If not (If you have at least 2 different classes where you want to use your constants) you should declare your class with constants as a top-level class with private constructor to unable to instantiate this class.

Upvotes: 0

Related Questions