All posts
Published in design patterns

Do you think long functions are a good idea?

Profile image of Atakan Demircioğlu
By Atakan Demircioğlu
Fullstack Developer

People always ask questions like, “How long should functions be”, “When is a function too long?” and so on.

Do you think long functions are a good idea? image 1

I will try to share my ideas about this.

Do you think long functions are a good idea?

I can hear that you are saying a big NO.

Also if I ask you, how often you see long functions you will probably say “Generally”.

How long is long?

Do you think 1000 lines are long? (Probably you will say: Absolutely!)
Do you think 100 lines are long? (Probably you will say: Yes!)

We don’t have a standard

Some guys are saying, If you see the function in the entire window it is not long. (Oh my gush! What is the font size?? :D)

The length of the function is not about lines of code. It is about details and we need it to keep one.

So here we need to understand SLAP. Let’s explain it.

What is SLAP?

  • The Single Level of Abstraction Principle is commonly known as the SLA principle
  • The idea is very basic. All the code inside a method should be at the same level of abstraction.
  • This will provide a lot of testability and readability to your code.
  • SLAP principle does not necessarily mean that your code will be shorter, it just means that it will be easier to read.
  • Also, it will provide a better maintainability

Let's make an example.

Just basically in this example, let's find if the first letter is capitalized and ends with a dot.

Please imagine in a real case, this is just an example.

Note: We can write this function better (better naming, checking is null or undefined and etc.) or I can miss some cases but it is not the case here.

  • This example violates SLAP
  • Cognitive load is high
  • It is not readable
  • Hard to maintain
  • Not testable (How we can test a string starting with uppercase? :D)

Ok, Let’s make some improvements

How about for now? I think it is better :)

  • cognitive load reduced
  • All functions are in the same level of abstraction
  • It is readable
  • We can test isFirstLetterCapital, and isEndWithDot separately (testable)

My final words that hear from Venkat;

A good code reads like a story, not like a puzzle

References