Function length

Original author: Martin Fowler
  • Transfer

Throughout my career I have heard many arguments about the length of a function. A deeper question - when does the code need to be moved to a separate function? Sometimes recommendations are based on size, for example, the function should fit on the screen. Others are based on reuse - any code used more than once must be put into a separate function. But if the code is used only once, then you can leave it in place. It seems to me that the argument about the separation of intent and realization has a lot of meaning. If you need to spend time looking for a piece of code to understand what it is doing, then you need to put it into a function and give it a name that answers the question "what." Then the next time the meaning of the function will immediately be obvious, and in most cases you will not care about how the function does its job.

When I began to apply this principle, I developed the habit of writing very small functions - usually no more than a few lines. Any function longer than six lines already smells. It is quite common for me to have a function with one line of code. Kent Beck once showed me an example from the original Smalltalk system, and it helped me to really understand that size is not important. Smalltalk in those years worked on black and white machines. If you needed to highlight text or graphics, you had to reverse the video. The class in Smalltalk, responsible for the schedule, contained the 'highlight' method, and in its implementation there was only one line - a call to the 'reverse' method. The name of the method was longer than the implementation, but it did not matter, because there is a large distance between the intention and implementation of this code.

Some people worry about short functions because they care about the impact of calls on performance. When I was young, it sometimes mattered, but today it’s rare. Optimizing compilers often work better with shorter functions because they are easier to cache. As usual, in the optimization of performance, first of all, general recommendations make sense. Sometimes the correct solution is to return the code from the function back to its original place. But often the presence of small functions allows you to find other ways to optimize. I remember when people were against having an isEmpty method for lists. The standard way was aList.length == 0. But here is just the case when the name of the function indicates the intention, and this can help with performance if there is a faster way to determine the emptiness of the collection,

Small functions like this only work if the names are good enough, so you need to pay attention to this. Over time, your skill will improve, and this approach can greatly increase self-documenting code. Functions of a higher level can be read like a story, and the reader chooses which functions to delve into if you need to know the details.

Also popular now: