Tuesday, December 12, 2006

Protected Find

One of the greatest professional compliments I've ever received was regarding a system that I designed and developed. The purpose was to provide an interface for numerous reporting systems to funnel reporting data into a unified location. I designed the system so that all data was retrieved via task specific finders (i.e. :find_agreement_number, :find_current_document_type). As a result, if the database changed, the methods could still be used (albeit with a tweak to the internal logic). Since I was working in a compiled environment where changing a table meant recompiling the functions that directly accessed the table, the need for public finders was required.

The compliment I received was that 6 months after the design was done, the vendor's system that we were integrating with required a major upgrade and changes. And in order to make my system work, they just pointed the finders to a different table, and presto things were working again.

Now what does this have to do with Ruby on Rails? Today I was having a conversation with a co-worker regarding find. After some discussion, I came out and said I really wish :find were a protected method. Find is a very powerful method that allows you to fully access all data from anywhere. This power exposes your your view, controller, and other models to the risk that your model will change. To reduce this risk, I feel it is important to create specific finders in your model and test them. Also, if you use :find_by_name (a free method on any table that has a :name column), you should also write a test for this (at a minimum making sure that your model responds to that particular find).

The entire goal of creating specific finders is to make the maintenance of a project easier. In addition, it is much easier, in Rails, to test models than controllers or views.

No comments: