Home Ruby: Clean your code!
Post
Cancel

Ruby: Clean your code!

Minimize the number of “nested if statement”

“nested if statement” is normally considered as the code smell. We should try to minimize the number of “nested if statement”, though we cannot avoid using it completely.

if the ‘if statement’ is embraced by a loop and without ‘else’, use ‘next’ instead

original code:

1
2
3
4
5
6
7
8
9
 foo.each do |f|
   if bar
     if baz
       ...
     else
       ...
     end
   end
 end

It looks not quike clean, isn’t it?

cleaned code:

1
2
3
4
5
6
7
8
 foo.each do |f|
   next if bar
   if baz
     ...
   else
     ...
   end
 end

It looks much better to me.

use variable to eliminate the ‘if statement’

original code:

1
2
3
4
5
6
7
 if bar
   name = "Jevan"
   age = 24
 else
   name = "John"
   age = 24
 end

cleaned code:

1
2
3
 user_name = bar ? "Jevan" : "John"
 name = user_name
 age = 24