javadatabaseconstantscode-maintainability

java 1.5: Best practice to keep constants for column name of db tables?


Technology:

To avoid update of column name on multiple places on change of column name or tablename, i want to have a constant file for same.

I have following queries?

In above case employees is name of table and performance_desc is name of column name. So kind of tablename__columnname format is followed for naming a constant to avoid collision between two constants of two different tables if both have have column name.

One problem with this approach i see is that as database grows no of constants in this file will grow to thousands which is difficult to manage. Other problem is if table name is changed, i have to change prefix table name for all of tables.

this can solve some of issues with global file like table name change will lead to class name change only. One major issue with this is that i am using class for sole purpose of defining constants which is not good coding practice.


Solution

  • It sounds like you're asking all the right questions - you want to make the code more maintainable, but realize that this could get unwieldy and end up making the code worse rather than better. Think of something like "Color.RED, Color.BLACK".

    I've found that a reasonable amount of constants like this makes the code more readable. I don't think db column names belong in something like this, because

    I've seen db files like this with thousands of constants, including custom queries, parts of queries, etc. etc (even a gem like public static final String COMMA=","; to take care of the possibility that the spelling of commas will change in the future). At this point they devolve into "use once" strings, and nobody dares to change them.

    One other caveat about string constants - finals get compiled into your class as strings. So if you recompile the constant class, but not the class that uses the definition, it's possible to end up with the new definition not propagating.