82c793022ec1bce6ea7573bc27b2340b

Any idea about better code?

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 !

63b22ac9bff0cd55d8a91da4dbf00693

Dan Kubb

April 13, 2008, April 13, 2008 04:26, permalink

2 ratings. Login to rate!

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
82c793022ec1bce6ea7573bc27b2340b

pcorral.myopenid.com

April 13, 2008, April 13, 2008 11:26, permalink

No rating. Login to rate!

Thanks! :)

5170ca260dbd2cdfd5a887a4dba7636f

Jeremy Weiskotten

April 21, 2008, April 21, 2008 15:04, permalink

1 rating. Login to rate!

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
F04aeb28129f653b207e8b5d92706096

Adkron

April 22, 2008, April 22, 2008 03:03, permalink

No rating. Login to rate!

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
F04aeb28129f653b207e8b5d92706096

Adkron

April 22, 2008, April 22, 2008 03:08, permalink

No rating. Login to rate!

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
82c793022ec1bce6ea7573bc27b2340b

pcorral.myopenid.com

April 22, 2008, April 22, 2008 11:28, permalink

No rating. Login to rate!

Thanks!

Your refactoring





Format Copy from initial code

or Cancel