DEV Community


Discussion on: What is the ideal length of a code for you?

mattother profile image

It really depends who you talk to. I think it's more useful to ask what are the pro/cons for functions of varying length.

The biggest issue with longer functions is the scope of variable lifetimes gets bigger and bigger, so it becomes easier to couple variables in unintuititive ways. Ex.

def do_stuff():
    x = calculate_a_thing()

    # a bunch of lines of code...

    # has x changed?
    # is it still being used in the same context it was originally?
    # did somebody accidently start using it, not knowing it was already used ealier?
    # etc...
    f = another_process(x, y)

It's similar to the issues with global scope, it becomes harder to see where things are starting to couple in dangerous ways and usually becomes more difficult to maintain.

Also, the cognitive load required to retain everything that going on in the functions gets more and more difficult the longer it gets. I think if you look at a function and you're afraid to refactor it, that's probably a good sign that it's too long.

Some people like a consistent level of abstration too, personally I'm not convinced this is super important, but it can help to be cognizant of. Ex.

def build_something(values):
    summed = sum_the_values(values)
    process_the_values(summed, values)

# vs.

def build_something(values):
    sum = 0
    for v in values:
        sum += v
    process_the_values(summed, values)

Personally I do find readability suffers when methods are too small, but I like the idea of an IDE tool like xtofl pointed out.

Also, not directly related, but the number of arguments is usually a good sign a function is doing too much (and usually that an incorrect abstration is being used).

For classes, again really depends on the class, but if there are a lot of methods it's probably worth asking yourself if it's doing too much. I think better indicators are a large number of dependencies or functions lacking cohesion. Ex.

class DoingALot(object):

  def __init__(self, invoice_service, payment_gateway, datetime_service, token_factory, potatoe_generator):
    super(DoingALot, self).__init__()
    # ...

  def print_invoices(invoice_printer):
    # ...

  # If you're printing invoices and processing payments in the same class, your probably doing too much.
  def process_payment(payment_vo):
    # ...