Tuesday, 30 November 2010

Perl: Separating the persistence and the business model layers - Part 1

Today, thanks to modern Perl technologies a growing number of Perl project use DBIx::Class to access the database, and a MVC engine, such as Catalyst or other frameworks and a nice template engine to expose the application on the web. Usually, the framework tutorial assumes that you will use DBIx::Class to access and store your objects from your MVC controller. I think this approach is wrong for the following reasons:

- DBIx::Class is a perfectly fine ORM mapper but it's not a business model framework. You can add business code to the result Classes but what happens if you want to migrate some of your stuff to a NoSQL storage? Or change the way some stuff is stored in the DB. Things can and will get ugly.

- Dbic objects do not provide the flexibility you would need to implement common object oriented patterns. What if you want to use Roles, enforce interfaces, implement your own search facility? You'll eventually get so much application business code in your Dbic object that they will no longer look like dbic objects.

- Your web framework is directly fed with the ORM model, and because you want to code things quickly, you start putting business code in your controller, and this business code assumes you're using this or that ORM. And the rest will come. Web applications are difficult to test for regressions, especially if they use Ajax. Things will break without being detected before release, you will fix them quickly in your controller, and as time goes on, your shiny new application using modern Perl technologies will end up being as difficult to maintain as a good old CGI mud-ball.

- What if you want to turn your application into an API? Or if you want to make command line tools for quick administration, or for asynchronous runs? Well you can't. Because the your business logic is scattered everywhere, in all the layers of the application.

What we end up with this approach is our persistence layer and our MVC layer (and in the worst case our template layer) become polluted with a blob of sloppy hard to maintain business model code. Also the sad thing is that your business code IS your business' added value, so it shouldn't be considered polluting something else. I don't think MVC's and ORM's are designed to be the natural container of your business code. I think they should be kept, and loved, and used for what they are: an easy and fast way of making non-business related code thin and minimalistic.
Blob of business code longing for a home on its own

For the development of libsquare.net, I've designed a reasonably fast and easy solution to this problem. I'll be talking about it in the next part of this sequence.

No comments:

Post a Comment