Search code examples
rubyrubocop

Rubocop claims for too many 'if' statements


I am measuring my code for a Rails app using Rubocop. This is my code:

def ratings_treatment
    if @rating.advertise_id
      advertise = Advertise.find(advertise_id)
      rating_average(advertise)
    elsif @rating.product_id
      product = Product.find(product_id)
      rating_average(product)
    elsif @rating.combo_id
      combo = Combo.find(combo_id)
      rating_average(combo)
    else
      establishment = Establishment.find(@rating.establishment_id)
      rating_average(establishment)
    end   
end

It does not pass a test regarding if. It is claimed that there are too many if statements.

I thought of splitting the code into some checker methods, but was wondering if there is some better way to get good metrics and still write good code.


Solution

  • I think you could use a switch statement to assign the argument for rating_average:

    def ratings_treatment
      average = case
                when @rating.advertise_id then Advertise.find(advertise_id)
                when @rating.product_id   then Product.find(product_id)
                when @rating.combo_id     then Combo.find(combo_id)
                else Establishment.find(@rating.establishment_id)
                end
      rating_average average
    end
    

    Although Rubocop will complain with

    Style/EmptyCaseCondition: Do not use empty case condition, instead use an if expression

    You could also simplify your if expression:

    def ratings_treatment
      average = if @rating.advertise_id
                  Advertise.find advertise_id
                elsif @rating.product_id
                  Product.find product_id
                elsif @rating.combo_id
                  Combo.find combo_id
                else
                  Establishment.find @rating.establishment_id
                end
      rating_average average
    end