patternjavaMinor
Obtaining column status definition
Viewed 0 times
definitionobtainingstatuscolumn
Problem
I know exactly how I would handle this in PHP, Python, JS, and AS, but I want to confirm that this is the correct approach to Enums in Java.
I have a database view which has a status column. It will only ever have one of four values (in MySQL, I would have made it an enum type column, but the type doesn't really matter in my current context). Each directly maps to one of the values defined below.
Now, in my JSP, I loop
(Before anyone asks, because of the scope of this particular project, it doesn't make sense to make this an ORM.)
I have a database view which has a status column. It will only ever have one of four values (in MySQL, I would have made it an enum type column, but the type doesn't really matter in my current context). Each directly maps to one of the values defined below.
public enum StatusDefinitions {
NOT_STARTED("not started"),
IN_PROGRESS("in progress"),
COMPLETE("opted out"),
OPTED_OUT("complete");
private String desc;
private StatusDefinitions(String desc)
{
this.desc = desc.toLowerCase();
}
public String getDescription()
{
return desc;
}
public static StatusDefinitions getStatus( String desc )
{
desc = desc.toLowerCase();
for( StatusDefinitions it: StatusDefinitions.values() )
{
if( it.getDescription().equals( desc ) ) return it;
}
return StatusDefinitions.NOT_STARTED;
}
}Now, in my JSP, I loop
for(StatusDefinitions it: StatusDefinitions.values()) and have selected="selected" based on if(modelObjStatus == it). When pulling this from/pushing it to the db, I have status = StatusDefinitions.getStatus( rs.getString( "status" ) );. And there is where I have this sensation that I've missed something. Looping through all of the Strings and comparing them seems like I lose the benefit of the Enum. It would almost seem better to have a series of public static final Strings.(Before anyone asks, because of the scope of this particular project, it doesn't make sense to make this an ORM.)
Solution
To start with, this is not good:
Otherwise, this is pretty standard code. There are two things I'd note:
COMPLETE("opted out"),
OPTED_OUT("complete");Otherwise, this is pretty standard code. There are two things I'd note:
- If
descis coming from the database, you may have a risk of NullPointerException if it comes as null once.
- Instead of looping and searching, you can create a map from description to value once and use it each time. Since your set of values is so small, performance difference is probably minimal, so this is question of taste.
Code Snippets
COMPLETE("opted out"),
OPTED_OUT("complete");Context
StackExchange Code Review Q#2932, answer score: 6
Revisions (0)
No revisions yet.