Are long methods always bad?
- by wobbily_col
So looking around earlier I noticed some comments about long methods being bad practice.
I am not sure I always agree that long methods are bad (and would like opinions from others).
For example I have some Django views that do a bit of processing of the objects before sending them to the view, a long method being 350 lines of code. I have my code written so that it deals with the paramaters - sorting / filtering the queryset, then bit by bit does some processing on the objects my query has returned.
So the processing is mainly conditional aggregation, that has complex enough rules it can't easily be done in the database, so I have some variables declared outside the main loop then get altered during the loop.
varaible_1 = 0
variable_2 = 0
for object in queryset :
if object.condition_condition_a and variable_2 > 0 :
variable 1+= 1
.....
...
.
more conditions to alter the variables
return queryset, and context
So according to the theory I should factor out all the code into smaller methods, so That I have the view method as being maximum one page long.
However having worked on various code bases in the past, I sometimes find it makes the code less readable, when you need to constantly jump from one method to the next figuring out all the parts of it, while keeping the outermost method in your head.
I find that having a long method that is well formatted, you can see the logic more easily, as it isn't getting hidden away in inner methods.
I could factor out the code into smaller methods, but often there is is an inner loop being used for two or three things, so it would result in more complex code, or methods that don't do one thing but two or three (alternatively I could repeat inner loops for each task, but then there will be a performance hit).
So is there a case that long methods are not always bad? Is there always a case for writing methods, when they will only be used in one place?