Reputation: 1801
Suppose I have an entity for user (id, name, user_type, address, access_level, and_so_on)
Here 2 properties are important, user_type
and access_level
. We know that there will be a fix value in user_type and access_level field, but its hard to remember what is the meaning of 1 ,2 or 3, so we create constants for these values to access them by name. like if user_type value is 1, its a normal user, 2 mean CSV user, 3 mean admin user and 4 mean root user.
Normally I define these constants with in the same Entity Bean Class which contains the field to save this value in database (or where ever).
public UserBean implements IBean {
...
/**
* constant for user type
*/
public static final int USER_TYPE_NORMAL = 1;
public static final int USER_TYPE_CSV = 2;
public static final int USER_TYPE_ADMIN = 3;
public static final int USER_TYPE_ROOT = 4;
/**
* constant for Access level
*/
public static final int ACCESS_LEVEL_SILVER = 1;
public static final int ACCESS_LEVEL_GOLD = 2;
public static final int ACCESS_LEVEL_DIMOND = 3;
...
}
So my question is, what is the best place (and why) to define them? (I can think of, but you can define any method)
UserBean
class, auto entity generator tool might overwrite them). Upvotes: 1
Views: 1557
Reputation: 16526
As @R.J proposed, the best option is to create a separate enum:
enum UserType{
NORMAL, CSV, ADMIN, ROOT;
}
Pro:
takes less space
static types
code completion
Contra:
takes a bit more memory per entity (8 bytes vs 16 bytes at x64 architecture)
Other commonly spread option is to define these constants as integers in the superclass. This would give you less memory consumption and code completion (at least in IntelliJ Idea). Lack of this completion can be the main reason not to define these constants as integers outside the hierarchy.
Upvotes: 1