best practices in methods

22 views
Skip to first unread message

rodrigo coutinho

unread,
Nov 13, 2012, 7:22:56 AM11/13/12
to rubyonra...@googlegroups.com
Hello, 

Consider this code, it gets a mention and an array of tags.
It finds the mentions and add the tags.
But in my methods I keep using return if foo.nil?
or execute a line of code if a line is not nil.
Is there a better way of doing this kind of thing?
Thks

def add_tags_to_mention mention_id, *tags
mention = Mention.find mention_id
return if mention.nil?
tags.each do |tag_id|
tag = Tag.find tag_id
mention.tags.push(tag.to_mongo) if tag
end
end

Jordon Bedwell

unread,
Nov 13, 2012, 8:24:00 AM11/13/12
to rubyonra...@googlegroups.com
Personally I would handle that a bit differently in that I would have
the model handle building it's own tags and I would inject an array []
and then delete_if value blank? but to address your concern directly:

I would never return nil unless I have to. I know quite a few Ruby
programmers do not care about that situation but I always return
false, true or the value of the value I processed... there are a lot
of cases where I will also to opt to just raise but that really
depends... in your situation I would have built it on the model as
Mention.build_and_save_tags and then had it raise if it could not find
the mention because to me that makes the most sense. What I am saying
is to me `return false if mention.blank?` makes more sense to me. I
could go on a long explanation a mile long explaining the difference
between situations and why I chose my flow to work those ways but I'll
just leave it at I would prefer false before nil.

Juan Pablo

unread,
Nov 13, 2012, 8:58:33 AM11/13/12
to rubyonra...@googlegroups.com
Returning nil is a little bit ambiguous. Did the method finished
correctly or a condition wasn't met?
I always try to return something or throw an exception when needed.

I don't know if there's a "best practice" for that.
--
--
Mis mejores deseos,
Best wishes,
Meilleurs vœux,

Juan Pablo
------------------------------------------------------
http://www.jpgenovese.com

rodrigo coutinho

unread,
Nov 13, 2012, 9:13:05 AM11/13/12
to rubyonra...@googlegroups.com
Alright, based on your opinion of returning nil,I changed the method a little bit. In fact return false is better.
Thank you.

class Mention

def self.build_and_save_tags mention_id, *tags
mention = Mention.find mention_id
return false if mention.blank?
tags.each do |tag_id|
tag = Tag.find tag_id
if tag
mention.tags.push(tag.to_mongo)
mention.save
end
end
end
end

Reply all
Reply to author
Forward
0 new messages