Mailinglist Archive: yast-devel (144 mails)

< Previous Next >
Re: [yast-devel] Questions about some YCP Equivalents in ruby
Dne 15.8.2013 14:03, Ladislav Slezak napsal(a):
The are other possibilities for setting the default:

- Hash.new(<default>) - the hash returns the default when the key is missing,
sets the default when creating the hash

- my_hash.default = <default> - sets/updates the default, similar to the above
but can be used later (for already existing hash)

[...]

However there is another possibility, the new() method takes a block as well:
(see http://www.ruby-doc.org/core-2.0/Hash.html#method-c-new)

a = Hash.new do |h, k|
case k
when "fsid"
0
when "type"
:none
else
nil
end
end

I'm little late to reply, but I still feel that I should point out that setting a hash default is something that I consider a bad practice.

The reason is that it is *unexpected* (99.99% hashes in Ruby don't set the default and just return nil for keys that are not present) and not easily *visible* in the code.

To illustrate this, imagine I am debugging something and see code like this:

result = my_hash["key"]

Suppose that "result" is printed later in the log and it's value is non-nil.

Because hash defaults are *unexpected*, it's very likely that I would assume that the "key" key was in the hash. This assumption could be wrong if a default is used and could lead me to a wrong direction.

Now suppose I'd "expect the unexpected" and would want to check if a default is used. Now I'd encounter the *visibility* problem. I'd have to look where the hash is created and see if a default is set there. And that by itself is not enough, because the default could be set even at some later point, meaning any code that touches the hash is suspect. As a result, I could spend quite some time just by ensuring that the hash has no default.

Because of these issues, I think it's generally better to avoid hash defaults completely. It makes the code easier to reason about, which translates to less bugs and less time spent by debugging.

--
David Majda
SUSE Studio developer
http://susestudio.com/
--
To unsubscribe, e-mail: yast-devel+unsubscribe@xxxxxxxxxxxx
To contact the owner, e-mail: yast-devel+owner@xxxxxxxxxxxx

< Previous Next >