Function design should be as short as possible

Source: Internet
Author: User
"Well-designed functions are often relatively small, and the design of too many functions is often messy, or there is a lot of room for optimization ." Maybe you don't think it is necessary to discuss the size of a function, because the essence of function design is cohesion, and its size is just a manifestation. The reason above is necessary. Let's discuss the function size. My core idea of functions: I propose the concept of the minimum processing unit of code: a basic operation (assignment, comparison, etc.) and a function call (including calling

"Well-designed functions are often relatively small, and the design of too many functions is often messy, or there is a lot of room for optimization ."

Maybe you don't think it is necessary to discuss the size of a function, because the essence of function design is cohesion, and its size is just a manifestation. The reason above is necessary. Let's discuss the function size.

My core idea of functions: I propose the concept of the minimum processing unit of code: a basic operation (assignment, comparison, etc.) and a function call (including determining the return value after a call) are regarded as a minimum processing unit. Therefore, the minimum number of processing units for a function is less than 7. If they exceed 7, you need to consider splitting them into multiple functions (why 7? At the same time, no more than 7 persons can process the information ).

There is no limit on the minimum number. even if there is only one, it is necessary to exist.

In the following cases, I will split the function into smaller ones:

  1. You cannot see all the code of the function at a glance. If the function is too long to see all the code of a function at a glance, I will not hesitate to split it. I don't want readers to flip the screen, and I don't want them to look forward to it. Beautiful functions should let readers know at a glance what they are doing and how they are doing.
  2. There are too many local variables. If there are more than seven local variables, I will consider splitting the function. Too many variables mean that I have to record too many states, which will increase the burden on my brain and take too many things into consideration. This also means that I may not think deeply about function functions.
  3. Too many indentation. Too much indentation means that too much nesting, loop, or judgment, will lead to complicated logic.
  4. If you are using ctrl + c and ctrl + v. The code you write is not good enough (DRY, Don't Repeat Yourself ). At this time, you need to split the part you copied into new functions.
  5. Not at the same abstraction level. For example, there is an initialization function that requires initialization of configuration data, sockets, database connections, and channel status.
Void init () {config_init (); socket_init (); db_init (); int I = 0; for (I = 0; I <max_chn_num; I ++) // Initialize all channels {g_user_chn [I]. status = status_init ;...... }}

The initialization code of all channels in the previous function is not in an abstract level with others. we should encapsulate it:

Void chn_init () {int I = 0; for (I = 0; I <max_chn_num; I ++) // Initialize all channels {g_user_chn [I]. status = status_init ;...... }}
How small can a function be at least?

The best functions I have ever seen:

int max(int a, intb)  {  return a > b?a:b;  }  

This function is very small and has only one row, but it has the following significance: at the function call point, we know at a glance that it is to obtain the maximum values in a and B, rather than analyzing a> B? A: logic of B. This can save the programmer's mental cost and achieve a goal: a beautiful function should let the reader know at a glance what he is doing and how he is doing it.

The biggest obstacle to small functions: performance

For beginners of programmers, the biggest obstacle to small functions is that they have no experience in understanding the advantages of small functions and have no experience in splitting large functions into smaller functions.

For experienced programmers, the biggest obstacle to small functions may be performance concerns.

Do not optimize performance too early. We generally think that the bottleneck of the program is generally not the bottleneck of the program: We need tools to determine the real bottleneck, and 20% of the code consumes 80% of the performance, before optimization, find the 20% code. Function calls consume resources and performance, but is this a performance bottleneck of the program? What is the percentage of consumed performance to the overall performance? This is not clear when writing code. Therefore, my opinion is that we would rather choose short functions for clear and simple design, so that the performance can be optimized faster and better later in the project.

Many people are questioning the max function instance I listed above. if he calls a small number of instances during the running period, the impact on performance can be ignored and the readability is obtained, clarity is of great value. in turn, if the number of calls is large, it becomes a performance bottleneck, then it can be optimized quickly using other methods after the program is compiled. There are not many program bottlenecks.

For the performance consumption produced by function calls, I will take the time to test the usage.

Final suggestion: During the training of new employees, it is found that new programmers are generally not sensitive to the function size. Therefore, I suggest you try to write a function of about 10 rows (or even smaller), and then you will find that a small function is of great power.

This article is available at http://www.nowamagic.net/librarys/veda/detail/90.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.