In the new project, we have built recently at Yoolk
. I really enjoyed a lot of refactoring the app.
There are things which always bother me a lot is the if/else
statements. I see them all the time. In my views, if/else
should be used at the low level of coding. We should not use them too much because it doesn’t make the code readable.
I remembered vorleak, my coworker, and I are moderators in a study group long time ago about Principles of Refacoring. Two principles that really inspires me quite alot: less code == less bugs and write code for human, not for machine.
It looks simple to experienced Rails
developers, but it’s useful for novice people. Here are some tips to reduce if/else
statements:
- Use
find_or_initialize_by
,find_or_create_by
method
As the method name, it’s a cleaner way to get/create objects without if/else
.
1 2 3 4 5 |
|
Be sure to check more about these methods if you didn’t know on http://api.rubyonrails.org/classes/ActiveRecord/Base.html in the Dynamic attribute-based finders section.
- Use
try
for possible nil object
Invoke try
for object that could be nil. It’s more convienient than doing a check by yourself.
1 2 3 4 |
|
However, don’t confuse with the below situation.
1 2 3 4 |
|
Try
also be called with block as well so that you can call multiple methods in a scope of try.
1
|
|
Check this document, http://api.rubyonrails.org/classes/Object.html#method-i-try as well.
- Use
||
operator +presence
method
The ||
is a common idiom in Ruby. However, it doesn’t work well if the first operand is empty string. The presence
method will return nil instead of “” if the object is `blank?“, otherwise it return the actual object back.
1
|
|
- Use default value
Use default value so that you don’t else clause.
1 2 3 |
|
- Keep the if/else logic in fewer places
Wrap them in a function and reuse it where it is possible. Sometimes, it ‘s hard to extract it into function because they are slightly different. Try to write in general context, think about its behavior, and make it fit.
If you feel you are doing too much if/else
, go back one step why you are doing that way. Try to use the correct objects that fit to your scenarios.
Here is my coworker’s version generating the last 12 months stats. He manipulates the string
object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
Here, it’s my version, much shorter and less code.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 |
|
Polymorphism
+Factory pattern
I recommend you read the book from Martin Fowler, Improving the Design of Existing Code.