Skip to content

Instantly share code, notes, and snippets.

@bhardin
Last active December 28, 2015 00:49
Show Gist options
  • Save bhardin/7416214 to your computer and use it in GitHub Desktop.
Save bhardin/7416214 to your computer and use it in GitHub Desktop.
Question for Avdi

When checking for valid input, we could raise an exception to make it more helpful to the developer doing the implementation.

Current code:

def initialize(params)
  super
 
  raise ArgumentError, "Must provide results base dir." unless params.has_key?("dir")
  @dir = params["dir"]
end

According to Confident Ruby it seems this is a bad pattern. The right pattern, would be the following:

def initialize(params)
  super
 
  @dir = params.fetch("dir")
rescue KeyError
  raise ArgumentError, "Must provide results base dir."
end

Is this correct? If so, our issue with this is what if something in super raises KeyError?

@avdi
Copy link

avdi commented Nov 11, 2013

I'd write this as:

def initialize(params)
  super

  @dir = params.fetch(:dir) do
    raise ArgumentError, "Must provide results base dir."
  end
end

I believe this strategy is covered in Confident Ruby.

@bhardin
Copy link
Author

bhardin commented Nov 12, 2013

@avdi

Okay. I think my example is too simplistic. If I want to use the @dir instance variable after fetching. How would you stripe it?

def initialize(params)
  super

  @dir = params.fetch(:dir) do
    raise ArgumentError, "Must provide results base dir."
  end

  ## Do something
end

@avdi
Copy link

avdi commented Nov 13, 2013

I think the disconnect here is that I don't think of the #fetch--including the raise--as failure handling code. It is checking input (and possibly generating, but not handling, an exception). So the whole stanza falls under the heading of "handling input" to me.

@bhardin
Copy link
Author

bhardin commented Nov 13, 2013

I have to think on this a bit. Let me continue using the philosophy and post a more thorough example when I come across one. Thanks for being helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment