Dylan Richards
Dylan Richards

Reputation: 786

What are the drawbacks of using a hash instead of a conditional?

One pattern I like to implement in order to make my code more declarative is to replace a long conditional like this:

def make_a_decision(value)
  if value == 1
    "One"
  elsif value == 2
    "Two"
  elsif value == 3
    "Three"
  end
end

With a hash like this:

def make_a_decision(value)
  { 1 => "One",
    2 => "Two",
    3 => "Three"
  }[value]
end

I like doing this because it replaces a conditional with an object that simply needs to respond to []. It's also easier to read, in my opinion, partly due to the DRY nature of the hash.

I don't see any other Rubyists doing this, though. Why not?

Upvotes: 0

Views: 156

Answers (1)

Artur Martsinkovskyi
Artur Martsinkovskyi

Reputation: 361

  1. This approach uses more memory because it creates a new hash instance every time you call this method.
  2. It is less readable than the original version for me.
  3. Most likely this code will be changed and this change may involve some other condition than simple equality. Then, you will have to refactor the whole thing to implement the change.
  4. Remember, DRY is not always a good thing. Think about reasons for your code to change before deduplication. DRY what is being highly duplicated already, but not prematurely.

Upvotes: 0

Related Questions