Search code examples
sqldatabasefunctional-programminglisp

Are Databases and Functional Programming at odds?


I've been a web developer for some time now, and have recently started learning some functional programming. Like others, I've had some significant trouble applying many of these concepts to my professional work. For me, the primary reason for this is that FP's goal of remaining stateless seems quite at odds with the fact that most web development work I've done has been heavily tied to databases, which are very data-centric.

One thing that made me a much more productive developer on the OOP side of things was the discovery of object-relational mappers like MyGeneration d00dads for .Net, Class::DBI for perl, ActiveRecord for ruby, etc. This allowed me to stay away from writing insert and select statements all day, and to focus on working with the data easily as objects. Of course, I could still write SQL queries when their power was needed, but otherwise it was abstracted nicely behind the scenes.

Now, turning to functional programming, it seems like many of the FP web frameworks like Links require writing a lot of boilerplate SQL code, as in this example. Weblocks seems a little better, but it seems to use kind of an OOP model for working with data, and still requires code to be manually written for each table in your database as in this example. I suppose you use some code generation to write these mapping functions, but that seems decidedly un-lisp-like.

(Note I have not looked at Weblocks or Links extremely closely, I may just be misunderstanding how they are used.)

So the question is, for the database access portions (which I believe are pretty large) of web application, or other development requiring interface with a SQL database we seem to be forced down one of the following paths:

  1. Don't use functional programming.
  2. Access data in an annoying, un-abstracted way that involves manually writing a lot of SQL or SQL-like code a la Links.
  3. Force our functional language into a pseudo-OOP paradigm, thus removing some of the elegance and stability of true functional programming.

Clearly, none of these options seem ideal. Has anyone found a way to circumvent these issues? Is there really even an issue here?

Note: I personally am most familiar with LISP on the FP front, so if you want to give any examples and know multiple FP languages, LISP would probably be the preferred language of choice.

PS: For issues specific to other aspects of web development see this question.


Solution

  • First of all, I would not say that CLOS (Common Lisp Object System) is "pseudo-OO". It is first class OO.

    Second, I believe that you should use the paradigm that fits your needs.

    You cannot statelessly store data, while a function is flow of data and does not really need state.

    If you have several needs intermixed, mix your paradigms. Do not restrict yourself to only using the lower right corner of your toolbox.