Skip to content

Coding guideline points

nikhilgoyal22 edited this page May 16, 2016 · 2 revisions

Very important

  • Look for areas in a code block if it can be written compactly once you have finished coding the logic.
  • Practice and ownership to make the code better are primary things.

Guidlines

  1. DRY - Don't Repeat Yourself. As soon as, the code starts repeating second time, abstract it out in a method and use the method

  2. Use local variable to hold the value of Jquery selector and use it if needed multiple times.

     //bad
     jQuery(‘#id’).css('..', ..)
     ....
     ....
     jQuery(‘#id’).html('..')
    
     //good
     var elem = jQuery('#id')
     elem.css('..', ..)
     ....
     ....
     elem.html('..')
    
  3. Omit use of unnecessary if/unless. In the following cases, if statement is unnecessary

     #empty array will not execute anything
     if arr.present?
       arr.each do |obj|
         ……
       end
     end
    
  4. Limit the usage of instance variables (specially for rails, usage mainly for views/partials which is in controller)

  5. Use consistent spacing (between operators, comma etc.)

  6. Use consistent indentation preferably 2 spaces.

  7. In Javascript,

    • if string is sufficient. No need for if string != ''
    • if array.length is sufficient. No need for if array.length == 0
  8. Do not use unnecessary intermediate variables which are not used in a function.

    • In javascript

         //unnecessary usage of variable value
         function test(){
           var value = jQuery('#input-id').val();
           return value;
         }
      
    • In ruby

         #unnecessary usage of variable val
         def org_status(user)
           status = user.organization.status
         end
      
  9. In ruby, prefer using each, map, select, each_with_index instead of for (preference to map/select/reduce etc. if the work can be done by them)

  10. Discourage the usage of eval. Instead use send wherever necessary.

  11. If you are looking for nil and there is any possibility of false turning up, then look for nil explicitly. (by .nil? Or == nil)

  12. use unless and until in place of if not and while not respectively.

  13. use modifier form if single statement (ternary operator or single statement if or unless etc.)

  14. While using methods like which return true/false like present?, empty? in conditional statements, omit usage of == true. if arr.present? is sufficient.

  15. Use constants for static data in a class in ruby

  16. Take care of scope of variables and avoid using global variables

  17. Some useful references/links for more information

Clone this wiki locally