Mohan pd.
Mohan pd. Author of The Coders Blog. Also a professional fullstack javascript developer working with various tech company and client around world.

How big a function should be ?

Sep 07, 2019 · 2 minutes
How big a function should be ?

It is good to have a function which is small, pure and will perform only one thing and do it very well. Let look at the point which you should include while writing a function in any programming language.

Before start, in simple word :

Extract till you drop

First rule of functions is that they are small

Extract the function as small as possible. It will help you write a cleaner and error free code with high testability.

They are smaller than that

You should always re-think about the way to make them smaller then they are. If you can think of smaller function then optimize it.

Lots of little well-named functions because they will save you and everyone time.

Little well name functions are very clear and concise for other developer to understand. For example, A function with the name Array.sort() is well name and we can understand it will sort array without any doubt. Though there might need a longer name in real world programming but we can always find a worthy name to explain it function in straight forward way.

Most of us don’t have to worry about efficiency of function calls.

Theoretically, yes too many function will make a program slow. But, the answer of HOW MUCH ?

Negligible.

Will it affect performance ? Should I stop writing functions ?

No Way. Never. For 99% apps this is just a few extra instructions and stack operations. It is totally insignificant when compared to the execution time for your whole program.

Making functions small save time.

It is easier to understand, debug and write a smaller function. So small functions always saves time.

Functions do One Thing.

It is important, that function need to do only one thing and do it very well. Attempting to do a lot of things inside a single function will make it impossible to test and understand.

They do it well, and do it only.

We should always make sure they do it very well.

If you can extract one function from another, you should.

Obviously, if function can be extracted then you always extract it.

Classes hide in long functions.