Shivamyadav's avatar

Is it good having approximately 900 lines of a function?

My senior uses the repository patterns to work with the controller business logics. In the function he has the create and update method to create/ update the resource and other side effects to perform actions whenever resource gets created or updated and both were approximately 900 of lines.

That was really too hard to understand it and overwhelming for me to just looking at the no of the lines in the function.

How long no of lines any function could have?

0 likes
9 replies
Glukinho's avatar

It is totally a matter of taste. However 900 lines seems far too many.

Some say a class/method/function should fit a screen without scrolling.

1 like
ranto's avatar

I second this. It really a matter of taste.
Sometimes you cannot avoid writting a large function and then never have the time to really write a readable function.

I prefer small functions and this is what I do when I encounter a massive function inside the codebase:

  1. I make sure all the task I had to do are done. I never refactor old code when I have business things to ship.
  2. Identify code blocks on the larger function that do a single task. Eg: check for some condition, do a business logic, etc
  3. Move those to a separate function. This could be a private function on the Repository or an action if you like the action pattern, etc. This might heavely deppend on your preferences or codebase standars.
  4. Make sure I don't break any test.

Just don't overcomplicate things. Write code for the person who is going to read it 3 months lated.

kevinbui's avatar

900 lines are way too much for a function and that should be refactored to tiny ones.

According to the most comprehensive resource on clean Code, the book Clean Code by Uncle Bob Martin. Each function should only contain 3-4 lines, at the same level of abstraction.

"The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that."

Robert C. Martin

I must admit 3-4 lines per function is a bit hard to achieve. We can aim for at most 10 lines per function for the most part.

Small functions are crucial to clean code and readability. Looking at the Laravel source code, thousands of people can grasp and contribute. Monster functions and chunks of code are only maintainable to whoever wrote them in the first place.

The unfortunate reality is, the majority of developers don't care much about clean code or small functions. Still, I always strive for them.

Please or to participate in this conversation.