Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method refactoring

Tags:

refactoring

How many lines of code can a method have with a good design before you need to make the design better?

like image 780
dexter Avatar asked May 22 '26 12:05

dexter


2 Answers

Lines of code is an incomplete metric to use for refactoring. Cyclomatic Complexity should be used in conjuction with LOC as a decent gauge for when to refactor.

A decent guideline is

LOC > 80 || CC > 10 == "Time to refactor"

Chances are you will hit a Cyclomatic Complexity > 10 long before you ever reach 80 lines of code.

Of course there are a litany of other metrics to consider as well:

  1. Afferent Coupling: How many methods depend on this method
  2. Efferent Coupling: How many methods does this method rely on
  3. No. of Parameters
  4. No. of Varialbes used

You can go pretty in depth, but all this to say that determining when to refactor can't be decided with a blanket rule like "Thou shalt not have more than 40 lines in any method!"

like image 128
Josh Avatar answered May 25 '26 21:05

Josh


There is no accepted rule. It should be as simple to read as possible. If that means taking 5 lines of a 10 line block and putting them in their own method, then so be it. But sometimes it can be fine to have 50-line methods. Just do what you think you'll understand best in 6 months time.

like image 45
Nathan MacInnes Avatar answered May 25 '26 21:05

Nathan MacInnes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!