---
title: Switching on an Attribute of Another Object
teaser:
tags: web,ruby,good code
author: []
published_on: 2011-07-08
---

> It is a bad idea to do a switch based on an attribute of another object. If
> you must, it should be on your own data, not someone else's. -
> [Refactoring](http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672)
> by Martin Fowler

We're reading Refactoring as part of an internal book club. This quote
reminds me of the [Feature
Envy](https://github.com/troessner/reek/wiki/Feature-Envy) code smell.

    class Cart
      def price
        @item.price + @item.tax
      end
    end

If most of the work in a method is being done on another object (@item), the
method should be on that other object.

If you haven't played with Kevin Rutherford's
[Reek](https://github.com/troessner/reek) gem before, it's a neat way to
find smells like Feature Envy in your Ruby code.
