Small functions: Nine benefits of shortening your Functions

Source: Internet
Author: User

 

Small Methods: Nine benefits of making your methods shorter

Small functions: Nine benefits of shortening your Functions

Note: The English version of this article is fromHttp://langrsoft.com/articles/smallMethods.shtml. Translation does not change the copyright of the original article. The Chinese version is copyrighted by myself.

I 've espoused, on using occasions, making your methods short. the pattern composed method, defined by Kent Beck in Smalltalk best practice patterns, says that methods shoshould do things only at one level of each action. methods shoshould be short; a good size for smalltalk methods is one to a half-dozen lines. that translates to about one to twelve lines (not counting braces !) For Java methods.

I recently engaged in a discussion at javaranch where someone thought "20 to 25 lines" was too short. after being taken aback, my response was that there are missing reasons that your average method size shoshould be considerably smaller. here are nine benefits to short methods:

In many cases, I have shown that short functions are supported. The composed method pattern defined by Kent Beck in Smalltalk best practice patterns indicates that a function can only be abstracted at one level. The function should be short; for smalltalk, the function size should be one to six rows. It should be one to twelve lines translated into Java (excluding braces !).

I recently participated in a discussion in javaranch, where some people think "20 to 25 rows" is too short. Surprised, my response is that there are many reasons for your average function size to be quite small. The following are nine benefits of using small functions:

  1. Maintenance costs.The longer a method, the more it will take you to figure out what it does, and where your modifications need to go. with shorter methods, you can quickly pinpoint where a change needs to go (fig if you are coding using test-driven development ).
  2. Code readability.After the initial learning curve, smaller methods make it far easier to understand what a class does. They can also make it easier to follow code by eliminating the need for scrolling.
  3. Reuse potential.If you break down methods into smaller components, you can start to recognize common activities actions in your code. You can minimize the overall amount of code dramatically by reusing these common methods.
  4. Subclassing potential.The longer a method is, the more difficult it will be to create valid tive subclasses that use the method.
  5. Naming.It's easier to come up with appropriate names for smaller methods that do one thing.
  6. Performance profiling.If you have performance issues, a system with composed methods makes it easier to spot the performance bottlenecks.
  7. Flexibility.Smaller methods make it easier to refactor (and to recognize design flaws, such as feature envy ).
  8. Coding quality.It's easier to spot dumb mistakes if you break larger methods into smaller ones.
  9. Comment minimization.While comments can be valuable, most are unnecessary and can be eliminated by prudent renaming and restructuring. Comments that restate what the code says are unnecessary.
    1. maintenance cost. the longer a function, the more costly it is to understand what it is to do and where it is to be modified. For small functions, you can quickly find out where to make changes (especially when the application test-driven development ).
    2. Code is readable. after the initial learning curve, small functions make it easier for you to understand what a class is going to do. And you don't have to move the window to understand the code.
    3. has the reuse potential. If you break down a function into small modules, you can identify the commonly used abstraction in the code. You can use these general abstractions to drastically reduce the total amount of your code.
    4. sub-classes . The longer the function, the more difficult it is to create a subclass to use this function.
    5. name. it is easier to name a small function because it does less work.
    6. performance measurement. if you encounter performance problems, a system using composed method can easily locate performance bottlenecks.
    7. flexibility. small functions make refactoring easier (and easily identify design defects, such as feature envy ).
    8. code quality. if a large function is divided into small functions, it is easier to locate hidden errors.
    9. minimize comments. although annotations are valuable, most annotations can be eliminated by careful naming and structure adjustment. It is unnecessary to repeat the comments that have been clearly stated in the Code.

You shoshould get the idea that most of the benefits are about improving the design of your system. breaking methods up into smaller ones obviusly leads to lots of smaller methods. you will find that not all of those methods shocould remain in the same class in which the original method was coded. the small methods will almost always point out to you that you are violating the basic rule of class design: the single responsibility principle (SRP ).

You should have discovered that most of the benefits are about improving system design. Decomposing a function into a small function will certainly bring about a large number of small functions. You will find that not all these small functions should be in the original class. Small functions almost always point out that you violate the basic rule of class design: the single responsibility principle (SRP )).

The SRP states that a class shoshould have only one reason to change. put another way, a class shoshould do one thing and one thing only. A class to present a user interface (UI) shocould do just that. it shouldn't act as a controller; it shouldn't retrieve data; it shouldn't open files; it shouldn't contain calculations or business logic. a ui class shoshould interact with other small classes that do each of those things separately.

Break a class into small methods, and you will usually find all sorts of violations of the SRP.

SRP specifies that a class can only be modified for one reason. In other words, a class should do only one thing. A class that presents a user interface (UI), it can only do the things it wants to render, and should not act as a controller or receive data; or open a file or include computing and business logic. A ui class should interact with other small classes, and those small classes should accomplish those things separately. Breaking a class into many small functions, you will usually find various violations of SRP.

Initially, you may find it more difficult to work with code with lots of methods. there is certainly a learning curve associated with doing so. you will find that the smart navigational features of your ide (for example, eclipse) can go a long way toward helping you understand how all the little methods fit together. in short time, you will find that well-composed code imparts much greater clarity to your system.

One oft-repeated resistance to short methods is that it can degrade performance in your system. indeed, method cballs are usually fairly expensive operations. however, you rarely create performance problems with more methods. poor performance can usually be attributed to other factors, such as IO operations, network latency, poor choice of algorithm, and other inefficient uses of resources.

At first, you may find it more difficult to use a large number of small functions. This is just a learning curve problem. You will find that the intelligent navigation feature of IDE (such as Eclipse) will be helpful for you to understand how these small functions are combined. In the short term, you will find that such Code gives the system better clarity.

The common resistance to small functions is that they reduce system performance. Indeed, method calls are usually expensive operations. However, you rarely have the opportunity to solve more function manufacturing performance problems. Low performance is usually caused by other factors, such as IO operations, network response, and poorAlgorithmAnd other inefficient resources.

Even if additional method CILS do noticeably impact performance (performance is not an issue until someone recognizes it as one), it's very easy to inline methods. the rule of performance is always: make it run, make it right (e.g. small methods), make it fast (optimize ).

Even if Redundant method calls have a significant impact on the performance (if no one notices the performance, it is not a problem), inline method is very easy. Performance rules are always: Let it run first, then make it correct (such as a small function), and then make it faster (optimized ).

While it's difficult to do, you can go too far and create too using methods. make sure each method has a valid reason for existing; otherwise inline it. A method is useless if the name of the method and the body of the method say exactly the same thing.

There are exceptions to every rule. there will always be the need for the rare method larger than 20 lines. one way to look at things, however, is to look at smaller methods as a goal to strive for, not a hard number. instead of debating whether 25 lines, 12 lines or 200 lines is acceptable, see what you can do to reduce method length in code that you woshould 've otherwise not touched. you'll be surprised at how much code you can eliminate.

Although this is not easy to do, you may have done too much and created functions. Make sure that each function has an appropriate reason; otherwise, inline. If the body of a function has clearly indicated what it does, this function does not need to be proposed separately. All rules have special cases. Sometimes a few functions require more than 20 rows. From the point of view, small functions are regarded as a goal rather than a fixed number. Rather than arguing that 25 rows, 12 rows, or 200 rows are more acceptable, it is better to see what you can do to reduce the number of rows of functions you don't want to touch. You will be surprised to find out how much code you can eliminate.

Few people promote pushing in the other direction. Increasing the average method size represents sheer carelessness or laziness. Take the time and care to craft your code into a better design.Small methods!

few people support the opposite idea. Increasing the average function size is totally careless or lazy. Take some time to fix the code and improve the design. long live small functions!

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.