/ ruby-on-rails

Quick Tips for Programming

I thought to create a quick tip post which is kind of lesson learnt, so that every time I learn something can add here and which could help others too.

These examples here are not something I have created to support the points which I have mentioned below. Whereas these are the real code snippets of a project. Where team has written code in this manner and given feedback to improve their code.

So I thought it would be better if I write a Lesson learnt post which could help other to be aware of mistake they can make while they are writing code.

1. Better comments
When we find some code which needs further attention and work, however we do not have time to work on that at present in that case always add following comments to your code.

  • If there is some missing logic or some additional logic is needed then add #TODO comment.

  • In case of unwanted code or broken methods use #FIXME comment.

  • If you find some methods need refactoring then use #OPTIMIZE comment. In some languages people use #XXX comment for the same.

   #TODO add code or implement logic
   #FIXME method A is broken
   #OPTIMIZE improve the code 

After adding these comments in ruby you can easily find all added comments by running a rake task

 $ rake notes
*Result*
  app/controllers/addresses_controller.rb:
  [  8] [OPTIMIZE]remove nested if
  [ 11] [TODO] add new method compute_dates
  [ 23] [FIXME] remove add_contact method

2. Misuse of ternary operator
It is good to use ternary operators while we are writing code. However we should use it correctly.
If we are using ternary for a Boolen value that does not sound a good approach
however if you are using it to get some other data type result in return then it make sense

Reason being, every conditional operator always returns a boolean value either true or false so in that case really do not need a ternary operator

e.g.
When we need non boolean resuls 
contact_name == "shivani" ? "Good" : "Bad"  <- [GOOD To USE]
contact_name == "shivani" ? true : false    <- [NOT GOOD To USE]
INSTEAD 
(contact_name == "shivani") <- [GOOD To USE]

3. Misuse of case for Boolean
as we always think to use case..when instead of neasted if..then etc. However some time we end up writing really such a code which we really do not need.

 e.g. in this code this case..when is used to just get the values as 
true and false whereas if you would have just used the conditional 
operator that could have given you the same result
  [BAD USE OF CASE..WHEN]
    my_value =
      case value
        when '1' then true
        when '0' then false
        else false
      end
    super(my_value)

  [INSTEAD]
    super !!(my_value == '1') 

Also names of predicate methods (methods that return a boolean value) should end in a question mark (?)

def is\_admin? 
    ....
 end

4. DO NOT use Pure String Conditions
Example of pure string condition:
Customer.where("first_name LIKE '%#{params[:first_name]}%'")

We should not use it as it is not safe and pure strings can leave you vulnerable to SQL injection exploits.
Other possible issue, it can also break your code when operand value is nil.

  last\_id = Note.unscoped.last.try(:id) # Now if value of last\_id is NIL  
  Note.unscoped.where("id > #{last_id}")
  #Now if last\_id returns a nil it will break the code with following error - 
  ActiveRecord::StatementInvalid: PG::Error: ERROR: syntax error at or near ")" 
  LINE 1: SELECT "notes".* FROM "notes" WHERE (id > )

INSTEAD use below mentioned syntax and it will protect you from security issues and also take care of NIL condition:
Note.unscoped.where("id > ?", last_id")

NOTE- I will be keep adding stuff to this list and also if anyone has any tips, which they want me to add here please send me message and I will update list so that we have a good collection of tips.

Shivani Thakur

Shivani Thakur

I am life time learner, passionate about technology, fullstack programmer and prefer clean deliveries. I am fearless, honest and vocal about my thoughts.

Read More