Sunday, February 05, 2006

Patterns

Christopher Alexander says:
Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution ...
So why is it so commonplace to use patterns where a problem doesn't exist?

Example 1. The Data Access Object was originally created to hide various data access APIs (LDAP, RDBMS, ODBMS, XML, EJB, etc.) behind an interface. But in reality most applications use a single data access API, and it's usually a relational database. So if you already use something like Hibernate as your data access framework, is it really necessary to wrap the data access in yet another class? Hibernate already abstracts you from the specifics of the target database (e.g., SQL Server, Oracle, PostgreSQL, etc.) Your queries are usually created in HQL and are written in the terms of your object model not the data model, so why add another layer that just delegates to Hibernate? Think about it, how many of your DAO methods look like "return session.getNamedQuery("someName").list();".

Example 2. The Data Transfer Object was originally conceived when Entity EJBs were in vogue. Because you wanted to use course grained data access and eliminate network traffic you'd package up your data and pass it over the wire in a DTO. But in a world where you're using something like Hibernate in the same VM why incur the overhead of DTOs and the marshalling they require. Hibernate can give you a domain object that you can disconnect from the Hibernate session and work with independently. Secondly DTOs are horribly brittle. If you change a domain object chances are pretty good you'll have to change a DTO.

I'm not saying the two patterns I used above are necessarily bad, it's just that they don't need to be used in every single case. People should look to patterns when they discover a problem with the way things are being coded. Remember the old agile mantra "Do the simplest thing that could possibly work". Don't try to build the most complex solution with every conceivable pattern. Instead think of building the simplest most elegant solution with the fewest lines of code. The people who have to maintain your code will thank you. Well okay, they might not thank you, but maybe they won't be cursing you every hour either ;-)

No comments: