Wednesday, September 18, 2019

Understanding Rubycritic Smells

Rubycritic is gem that wraps around static analysis gems such as Reek, Flay and Flog to provide a quality report of your Ruby code.

Because this gem was uses as Audit guidelines code quality in my company, I often faced hard time to adjust, optimizing and refactor my code.

I began to summarize Rubycritic detecting behavior and implement it in my code to avoid Smells and easier get at least Grade C to bare pass.

A few my conclusion things to consider when developing code according Rubycritic :


  1. Don't! Never! Avoid! Duplicity Code. Rubycritic love this think and will give you sudden great high score, enough to drop your Code Rating Grade.
  2. Evade complicated nested logic with multiple if, switch, etc. It's saver to use functions to handle logic rather than nested logic. Fox example

    // Rather than this
     if obj == "a"
       if obj1 == "1" && obj2 == "2"
         // Process
       elsif obj1 == "3" && obj2 == "4"
         // Process
       else
         // Process
       end
     elsif obj1 == "b"
       if obj1 == "1" && obj2 == "2"
         // Process
       elsif obj1 == "3" && obj2 == "4"
         // Process
       else
         // Process
       end
     else
      // Process
     end
    
    // Use this
     if obj == "a"
       process(obj1,obj2)
     elsif obj1 == "b"
       process(obj1,obj2)
     else
      // Process
     end
    
    
  3. Evade complicated nested loops with multiple each, for, etc. It's saver to use functions to handle loops rather than nested loops. Fox example

    // Rather than this
     data_sources.each do |data_source|
      data_source.each do |data|
      end
     end
    
    // Use This
     data_sources.each do |data_source|
      process(data_source)
     end
    
    
  4. If your function using nested hash, redeclare multiple used nested hash using variable.

    // rather than
    if params[:id] == '1'
      user = User.where('id = ?',params[:id])
    end
    
    // Used This
    id = params[:id]
    if id == '1'
      user = User.where('id = ?',id)
    end
    

  5.  To combine Hash uses:  .merge!()

          params_data_assign = {}
          params_data_assign[:password_salt] = BCrypt::Engine.generate_salt
          params_data_assign[:password_hash] = BCrypt::Engine.hash_secret(password, self.password_salt)
          params_data.merge!(params_data_assign)
    


  6. Use method = const_get(method) to change string into Model Constant. (surprisingly isn't it?).

      def myfunction
       my_return = obj == 'User' ? 'User' : 'Member'
       process_my_return(my_return)
      end 
      def process_my_return(my_return)
        method = const_get(my_return)
        data = method.where('id = ?',1)
        // Process
      end
If you have found something more than this or have more effective way. Please, tell us so we can share about this problem more.

Share:

0 comments:

Post a Comment