Plasticx Blog

Capable of being shaped or formed

query method pattern, abridged version

Posted by Mike 07/30/2008 at 10:50AM

Kids that smoke pot grow up to be short adults

Like kids that start smoking pot before the age of 13 stunting their growth, almost every Java programmer has an aspect of their OO programming skills stunted. Namely the OO principle of “Favor ‘object composition’ over ‘class inheritance’.” from the GofF book about design patterns . Because you can’t do that naturally in Java one becomes heavily dependent on class inheritance and your ability to solve problems elegantly in Ruby is extremely disabled when first using the language.


What’s up Java Guy?:

arr = [1, 2, 3,]
if arr.size > 0
#do something

How’s it hang’n OO dude?:

arr = [1, 2, 3,]
if !arr.empty?
#do something
# fyi, in ActiveRecord there is arr.any?

The Fundamental Idea

Start looking at querying objects for their state instead of pulling their state out of them. When you start doing this you’ll come up on situations where the object is not providing a query method that you need. That is your entry point into the power of Ruby because you’ll start to learn how to open up classes and objects using various Ruby techniques to create the query method needed for the situation.

In the above code there is a comment that ActiveRecord defines #any? for its collections. See the definition of any? in association_collection.rb . Essentially #any? is just !arr.empty? The point being that Ruby didn’t provide an #any? method for collections so it was defined in ActiveRecord. There is no reason that you shouldn’t be doing the same in your code when you need a query method for your situation.

ReihH describes the query method pattern at depth in Ruby Patterns: Query Method and was the inspiration for this post.


Once you start applying the query pattern in your code you’ll want to follow up by understanding the following posts.

Posted in , , |

Web Statistics