Tags

Two Things I Avoid

by serge on July 30th, 2010

There are two things that smell bad to me: when database data leaks into code and when app code leaks into database. I’m not talking about SQL views, stored procedures, foreign keys, and other well known holy war stuff. I’d like to bring up some of “misplaced constants” problems.

Code constants that belong to database

Consider this example:

 
SPONSORED_PARTNER_IDS = [
    1234, 5678, 9101 #, ... etc
  ]

Here, prod DB was taken in order to look up the ids, and than those were hard coded into the code constant. It’s wonderful to observe how this seemingly harmless approach expands with time. Sometimes magic numbers don’t become less magic even after being put into well named constants.

Database tables that belong to code

Here’s the inverse pattern. Have you ever seen anything like this:

 
 SELECT * FROM content_statuses;
 
 id |   name    
----+-----------
  1 | Draft
  2 | Published
  3 | Hidden
(3 rows)

Here we have a content status dictionary in the database. But for what reason? For consistency enforced by foreign keys maybe, but I’m not sure it worth the burden of maintaining the table. The problem from design perspective here is more important however. What makes all those statuses different is code itself. If you do an INSERT and add another status, say “rejected”, it won’t change anything until you drop in some code changes that do all the associated special treatment to your content. This approach often breaks Common Closure Principle of component design.

Another way code leaks into database is “table algorithms”. Have you ever seen a table that contains pieces of SQL/PHP/Perl/Ruby code that are used by agile and generic algorithm? Often it comes as anticipation for future changes. The Holy Grail of code reuse probably is to make an algorithm that is so generic that it can handle any business request without change. All you have to do is update some data in the database. I’d rather call it code that leaked into configuration. Sometimes it transforms into a belief that marketing/content/admin folks will be able to make changes without even touching developers team. But more often than not, it ends up with everyone being too afraid to touch any of such code, and only one person being able to make “configuration changes” – the author of the code. With new requirements often come additional generalization and complexity. Same effort put into well thought modular, object oriented design could yield in good code that is complaint with Open Closed Principle (OCP) and located where it belongs – in files that are under control of VCS. It would still require some updates with new marketing requests, but those would land in code, and not DB migrations.

From rails

1 Comment
  1. Alex permalink

    Thanks for sharing your thoughs, Serge.
    Clean, easy and nice :)