||= [] idiom

On Sat, 23 Feb 2008 07:27:17 +0900, “Robert K.”
[email protected] wrote:

But all these points you mention do also apply to the Hash based
approach. You can even use the same wording, if you like:

@category_for = Hash.new {|h, tag| h[tag] = []}

Yes. I was thinking in terms of why to do the refactoring at all,
using my example refactoring as a point of reference, rather than
weighing the pros and cons of different refactorings of the original
code.

structure.
This is a good point; I would prefer add_to_category to just
category_for.

On the flipside, for small scripts that Hash based approach has the
advantage of being shorter (because no method is needed).

True, though shorter isn’t necessarily clearer. One of the
disadvantages
of using default blocks for hashes is the additional cognitive burden
when
reading the code: you must keep in the back of your mind that that,
“this
hash, it is a hash unlike any other.” I don’t think that’s a
significant
issue for small scripts, but it is why I tend to avoid the use of
default
blocks in larger scripts and libraries.

-mental

2008/2/22, MenTaLguY [email protected]:

category_for(resource.tag) << resource
This is an advantage for maintainability.
simply change this:
@categories[tag] ||= Category.new
end

It’s the DRY principle: Don’t Repeat Yourself.

If there is repetition in your code, it is harder to read (because
you have to mentally filter out the repeated parts to see the
differences – which are the important part), and you make more work
for yourself (because you must then edit many different places to
effect a single change, and are more likely to make mistakes).

But all these points you mention do also apply to the Hash based
approach. You can even use the same wording, if you like:

@category_for = Hash.new {|h, tag| h[tag] = []}

I was expecting reasoning that would highlight advantages of using a
method here. The only thing that comes to mind is that if you want to
exchange the implementation altogether, then a method based approach
is better. But in that case you’d probably do

def add_to_category(tag, item)
(@cat[tag] ||= []) << item
end

Because that abstracts away category creation and adding to the
structure. On the flipside, for small scripts that Hash based
approach has the advantage of being shorter (because no method is
needed).

Kind regards

robert

On Fri, Feb 22, 2008 at 6:15 PM, Robert K.
[email protected] wrote:

2008/2/22, Leslie V. [email protected]:

I may be wrong here but I read Thufir’s question differently: it seems
he is asking for the application of refactoring this into a separate
method.

Man! All my hard work!

On 23.02.2008 00:51, MenTaLguY wrote:

structure.
issue for small scripts, but it is why I tend to avoid the use of default
blocks in larger scripts and libraries.

All good and valid points! Thank you for this discussion!

Kind regards

robert