abstractionhard-coding

Benefits to using a database table instead of just hard coding a simple list of data if the data is consumed by 1 app


For a while, I've been told by a number of people that a listing of U.S. States (and territories) should be stored in a database table and cached for applications that use the information. The only reasons they give me for this is to promote normalization and because "it's how we've always done it".

Now if the list changes often because the scope of the application grows internationally (say to include Canadian Provinces), I can understand abstracting the list to a data table that would also indicate a country identifier as well. However, if the list is pretty much locked and only used on 1 screen of the application, is it worth doing the query and caching? Is the difference between storing an SMALLINT foreign key that much better than a CHAR(2)? Is it always practical?

Was just pondering this trend that I've seen with the companies that I've worked with.


Solution

  • I put them in the database, for a few reasons:

    1. It's just good normalization practice.

    2. Why should I hardcode any data in my application if I can avoid that by putting it in the database?

    3. Personally, I like the comfort of the guaranteed uniqueness property. When two tables point to the same foreign key, I know that they are referencning the same thing. When two happen to share the same two character code... well, then it's up to the application.

    4. Constraint Checks.... lots of two character codes are illegal, but the database won't be able to help you with that. It's a lot harder to have an illegal foreign key entry.

    5. Speed. I haven't benchmarked, so I may be wrong, but I bet having the database combine entries for you is faster than you doing it yourself. If you are using the state code for anything else (e.g., to get the non-abbreviated name of the state, or to maintain a list of valid zipcodes for that state ), a join is probably faster than whatever you would write.