1 2 3 4 5 6 7 8 9 10 11
def self.valid?(key) h=find_by_key(key) if !h.nil? total = h.total real = h.invitation_details_count (real < total) ? true : false else false end end
Refactorings
No refactoring yet !
Dan Kubb
April 13, 2008, April 13, 2008 04:26, permalink
This refactoring uses a guard clause to short-circuit the method at the beginning. Guard clauses are a clean way to exit out of a method if some condition isn't immediately met. Also since the comparison statement returns true/false, there's no need to use a ternary operator to explicitly return true or false.
1 2 3 4
def self.valid?(key) return false unless h = find_by_key(key) h.invitation_details_count < h.total end
Jeremy Weiskotten
April 21, 2008, April 21, 2008 15:04, permalink
Here's a one-liner...
1 2 3
def self.valid?(key) !(h = find_by_key(key)).nil? && h.invitation_details_count < h.total end
Adkron
April 22, 2008, April 22, 2008 03:03, permalink
Like Jeremy on I like my statements in the positive. I don't like a lot of ! if I can avoid them. So you add a little De Morgan's Law and you get the following.
1 2 3
def self.valid?(key) (h = find_by_key(key)).nil? || h.invitation_details_count >= h.total end
Adkron
April 22, 2008, April 22, 2008 03:08, permalink
Wait that doesn't work. I had the law messed up. De Morgan's LAw is: "~(p and q)" is logically equivalent to "(~p) or (~q)" . I think I may have made too far a leap. If I wanted to apply the law I would have had to put a ! in front of the whole thing. So I still would have my !. Sad sad me.
1 2 3
def self.valid?(key) !((h = find_by_key(key)).nil? || h.invitation_details_count >= h.total) end
Any idea about better code?