User talk:Jreidinger

Jump to: navigation, search

Ruby & Rails antipatterns

General rules


bad code:

 if a == nil or b.nil? 

why it is bad: ruby itself eval nil as false, so it is necessary only if variable is boolean so it should look like:

 unless a || b  # or if !a || !b

( I change 'or' to || because we evaluate variables and not workflow )

bad code:

 if a.nil? || a == "" 

Use rails method blank? in this case with same result.


bad code:

a = nil
  a = create_a()
rescue Exception => e
  log.error "Fatal"

if a

Don't rescue exception if you cannot do something usable without it (otherwise you hide errors). Usual thinks where you want rescue exception:

  • at top level to report user problem and how he can solve it
  • when operation which is done is only optional ( like read cache (recreate it slowly), log (don't log), write progress to user ( user will be more happy if you finish job even if they don't see it) etc...)
  • if it is know issue and you want translate exception to better one ( like if reading file fail, check if permission is correct, file exist etc.. and inform user better how to fix it)

Also you should never catch for exception ( unless it is "last catch"). You should catch only what you really want (usually ancestor of RuntimeError or IOError - [ruby exception hierarchy]