In my rails app, I have a method like this:
def cart
if user_signed_in?
@user = current_user
if @user.cart.present?
@cart = @user.cart
else
@cart = false
end
else
cart_id = session[:cart_id]
if cart_id.present?
@cart = Cart.find(cart_id.to_i)
else
@cart = false
end
end
end
Rubocop flagged this method as Method had too many lines
. Why is it bad to write a method with too many lines? What if we have to do a lot of work in it? How can I re-factor this and write good code?
One way is that you can refactor it using ternary operator, but at the cost of readability.
def cart
if user_signed_in?
@user = current_user
@cart = @user.cart.present? ? @user.cart : false
else
cart_id = session[:cart_id]
@cart = cart_id.present? ? Cart.find(cart_id.to_i) : false
end
end
Secondly, if you are compelled to write a very long method, it means there is something wrong with your Object Oriented Design. Maybe, you need to design a new class for the extra functionality, or you need to split the functionality in the same class by writing multiple methods that when combined, do the job of a single long method.
Why is it bad to write a method with too many lines?
Just like an essay with big paragraphs is harder to read, likewise a program with longer methods is difficult to read, and less likely to re-usable. The more chunks you divide your code in, the more moduler, re-usable and understandable your code will be.
What if we have to do a lot of work in it?
If you have to do a lot of work in it; it surely means that you have designed your classes in a way that isn't good. Perhaps, you need to design a new class to handle this functionality, or you need to split up this method into smaller chunks.
How can I re-factor this and write good code?
For that, I highly recommend to you a great book named: Refactoring by Martin Fowler, he is incredibly amazing at explaining how, when, and why to refactor your code.