Use Blank? To Avoid Code Smells in Rails
To improve my programming skills, I am refactoring some Ruby on Rails projects. I am using code smell tools like reek to do so.
One of the code smells reek checks for is NilCheck. Checking if an object is nil is a type of explicit type checking, indicating abstraction problems. If polymorphism is working then no explicit checks are necessary.
However in rails ActiveRecord objects - unless a default is set in the database - have their fields initialized to nil
. But after the object has been saved from a form, strings fields will be empty (""
).
How to condition on ‘presence of a string of length more than zero’? We can’t call length
since nil.length
throws an exception. And if we write string.nil? or string == ""
, we are making an explicit type check.
However, in rails, both nil
and String
respond to blank?
. Therefore string_variable.blank?
will fulfill the role of string_variable.nil? or string_variable == ""
nicely, avoiding code smells and unnecessary database defaults.