An example of procedural code made beautiful through object thinking.
by Rabbit
Take this top-down, procedural code:
@rules = @event.rules.reject { |rule| rule.id.eql?(@rule.id) }
What’s it doing? It’s returning a list of rules belonging to an object that are not the current rule. In other words, it’s returning all rules but one, specified by some argument.
While the code is not incredibly difficult, it could be easier. And easier is always good. In a perfect world, maybe it looks like this…
@rules = @event.all_rules_except(@rule)
Whoa! That’s a simple change, but it’s much easier to read, and possibly best of all, we can reuse this method anywhere AND change its implementation without breaking or revising existing code!
Object thinking is often a matter of going from, “Okay, now I need to do this, this and this,” to, “now I need to ask my object to do this.”