I’ve the following scenario. My application interacts with the database which contains some static tables. If I have to use that static information in the code level mostly for conditional code, what is the best approach.
For eg: I’ve a student database, which contains a static table student_type ( indicating hard-working, smart, lazy etc types ). In the code, I need to take action based on the student_type.
So, my code would look like this
studentTypeId = student.getTypeId(); // student constructed from database
switch (studentTypeId)
{
case HARDWORKING_ID :
// do something
case LAZY_ID :
// do something
break;
}
Well, in my code, I would either use constants or an enum to store type ids. But, isn’t this kind of replicating things in code since I already have type ids in database. If the type id in database changes I’ll have to change the same in my Enum which increases maintenance. Is there a better way to achieve this?
Thanks.
The question to ask is: does the addition of the row in the database imply a change in your java? If yes, go for the enum approach, and don’t worry about the duplication. If you’re going to have to change code anyway, for instance, to add new cases to your switch, then I usually find it’s a good idea to keep things simple.
Often in cases where you’re storing static data like this you’ve got other constraints that go with the data, and when you change the data in the database, you have to change the code that uses that data.
If you really really want to reduce the duplication, then you can go for a fully pluggable architecture, as suggested by Dave Newton. This could be implemented as a id -> class name relation for each id. You’d then instantiate the class and all of the logic associated with each id would be contained in that class. This isn’t always easy or possible. For your example, it may well be possible, but unless it’s done right, this can be complicated.
Also, it doesn’t solve all of your problems. You still have to develop the java, test it, and redeploy the new class. So actually, the amount of work you would save may be minimal.
It’s often easier to accept the small amount of duplication and just go with the simple solution.