[Codecomplete] Is it necessary to create a function?

Source: Internet
Author: User

The following is an excerpt from <code Daquan 2> [Chapter 7 high-quality subroutines]

What is a standard in programming? I believe no one can give a systematic theory, the author of "code Daquan" is describing the problems from design to implementation that many people are aware of and have not gone into depth, or are not aware, the system provides many details about software development. Hope to help everyone!

This chapter discusses the following issues:

Justification for creating a subroutine

Design on the subroutine Layer

Get a good name

How long can a subroutine be written?

How to Use subroutine Parameters

Special considerations when using functions

When to use the function and when to use the process

Macro subroutine and inline subroutine(Good content)

The subroutine here refers to a method or process to accomplish a specific purpose. Under what circumstances do you usually decide to create a subroutine? This answer may be difficult to understand. However, there is a complete analysis in <coding Daquan>.

1. Justification for creating a subroutine

A. reduce complexity

You can create a subroutine to hide some information, so that you do not have to consider this information too much during implementation. After the program is written, you can even forget these details, as long as you still remember how to use them.

B. Introduce intermediate and easy-to-understand Abstraction

Putting a piece of code into a well-named subroutine is one of the best methods to illustrate this piece of code. For example:

If (node <> null) then

While (node. Next <> null) Do

Node = node. Next

Leafname = node. Name

End while

Else

Leafname = ""

Endif

If it is changed to this sentence, it will be easier to understand:

Leafname = getleafname (node)

 

This function name getleafname provides a higher level of abstraction to make the code more readable, easier to understand, and reduce the complexity of subprograms that originally contain the above Code.

C. Avoid code duplication

If similar code is written in two sub-programs, it means decomposition, which is an error. At this time, we should extract the duplicate code from the two sub-programs, put the same part into a base class, and then put the differential code into the derived class. There is another way (such as C Language Development) to put the same code into the new subroutine, and then let the rest of the code to call this subroutine. This code is more reliable, because you only need to check a piece of code to verify the correctness of the code, and this will make the changes more reliable, because you can avoid the need to make the same changes, but made some slightly different changes.

D. subclassing)

Override: the number of new Code required for short and regular subprograms is less than for long and chaotic subprograms. If you can keep overwriting subprograms simple, you will also reduce the chances of making mistakes when implementing the derived classes.

E. Hide order

For example, if a program reads data from the user first and then the auxiliary data from a file, whether it is a subroutine that reads data from a user or a subroutine that reads data from a file, it should not depend on whether another subroutine has been executed. A clear example is to read the data at the top of the stack and then reduce the value of the stacktop variable. Then, we should put the two lines of code in a subroutine called popstack. Hiding such information is better than hiding it in the system.

F. Hide pointer operations

Pointer operations are generally poorly readable and error-prone. By isolating these operations within the subroutine, you can focus on the intent of the operation, rather than the details of the pointer operation. At the same time, if such and all can be completed in one location, you will be more confident about the correctness of the Code. If you find a data type that is more suitable than a pointer, you can also modify the program without worrying that it will damage the code that was originally intended to use the pointer.

G. Improve portability

You can use subroutines to isolate unportable parts of a program, so as to clearly identify and isolate the demonstration of transplantation.

H. simplify complicated Boolean judgment

In order to understand the process of the program, it is usually not necessary to study the details of the complex Boolean judgment. These judgments should be put into the function to improve the readability of the Code, because: (1) in this way, the details of the judgment are put aside. (2) A descriptive function name can summarize the purpose of the judgment.

I. Improved performance

By using subprograms, You can optimize the code in only one place. It is easier to find out which codes are less efficient in one place. At the same time, all the code of this subroutine can be used (either directly or indirectly) to benefit from one optimization.

J. Make sure all subprograms are small (NO)

If there are so many good reasons to write the code as a subroutine, this is unnecessary.

2. Operations that seem too simple and do not need to be written as subprograms

One of the biggest psychological barriers to writing a valid subroutine is reluctance to write a simple subroutine for a simple purpose. Writing a subroutine with only two or three lines of code may seem a little useful, but experience shows that a very good and small subroutine will be very useful.

Small subprograms have many advantages. One is that they can improve their readability. I wrote the following code in more than 10 places in a program:

Points = deivceunits * (points_per_inch/deviceunitsperinch ())

Most people can understand that this is a conversion from device unit to point. But it can be clearer, so I created a program:

Function deviceunitstopoints (deviceunits: integer): integer

Deviceunitstopoints = deivceunits *

(Points_per_inch/deviceunitsperinch ())

End Function

After using this subroutine to replace the Inline code, the dozens of lines of code in the program become the following:

Points = deviceunitstopoints (deviceunits)

This line of code is more readable-and even has reached the point of self-annotation.

This example also implies another reason for writing simple operations into functions: simple operations often become complex operations. For example, in some cases, if a device causes deviceunitperinch () to return 0, it means that the Division by zero must be obtained. Therefore, three more lines of code are required. The amount of work required is dozens of times before subprograms are implemented.

3. Get a good name

Note: Do not use Pinyin for function names, which may cause dialect pronunciation problems.

A. Describe all the things that the subroutine does

The subprogram name should describe all of its output results and side effects ). if a subprogram is used to calculate the total report amount and open an output file, it is not complete to name it compusereporttotals. Computereporttotalandopenoutputfile () is complete, but it is too long and silly. If you write subprograms with some side effects, you will have many long and silly names. The solution is not to change to another name, but to write a program in another way to solve the problem directly.

B. Avoid meaningless, fuzzy, or ambiguous verbs.

Some verbs have very flexible meanings and can cover almost any meaning. Subprograms such as handlecalculation (), objective mservices (0, outputuser (), processinput (), and dealwithoutput () do not explain what a subprogram is doing. Of course, handle is an exception when it uses the specific technical meaning of event processing.

If you change handleouput () to formatandprintoutput (), it is easier to see the function of this subroutine.

C. Do not use numbers to form different subprogram names.

A programmer writes all the code into a large function, creates a function for every 15 lines of code, and names them Part1 and Part2 respectively. This method of creating subprograms and giving subprograms life is shocking.

D. determine the length of the subroutine name as needed

Studies show that the optimal length of a variable name is 9 to 15 characters. A subroutine is generally more complex than a variable. Therefore, a good subroutine name is usually longer. On the other hand, the subroutine name is usually after the object name, which actually provides a part of the name for free. In short, the length of a subroutine name depends on whether the name is clear and understandable.

E. when naming a function, you must describe the return value. 

The function has a return value, so the function name should be based on the return value. For example, cos (), customerid. Next (), and pen. currentcolor () are both good function names, which accurately express the results to be returned by the function.

F. Add an object using a verb with a strong tone when naming a process

A process with function cohesion is usually an operation performed on an object. The process name should reflect what the process is doing, and an operation on an object requires a verb + object name, such as printdocument () calcmonthlyrevenues (), checkorderinfo () and repaginatedocument.

G. accurately use the opposite word

The naming rules used for naming can help maintain consistency and improve readability. Phrases like first/last are easy to understand, while combinations like fileopen and _ lclose are easy to confuse. The following lists some common confrontation phrases:

Add/Remove increment/decrement open/close

Beign/end insert/delete show/hide

Create/destroy lock/unlock source/Target

First/last min/MAX start/stop

GET/put next/previous up/down

GET/set old/new

H. Create naming rules for Common Operations

In some systems, it is very important to differentiate operations of different categories. Naming rules are often the simplest and most reliable method to indicate such differences.

In the code of a project I have done, each object is assigned a unique identifier. We have neglected to create a naming rule for the subroutines that return such object identifiers, and even have the following subroutine names:

Employee. Id. Get ()

Dependent. GETID ()

Supervisio ()

Candidate. ID ()

The employee class provides its ID object, which in turn provides the get () method; the dependent class provides the GETID method; the supervisor class sets the ID as its default return value; by the middle of the project, no one can remember which object should use which subroutines, but at this time too much code has been written. In this way, everyone in the project team has to spend unnecessary effort to remember the syntax details of getting IDs on each object. These problems can be completely avoided by establishing naming rules for getting IDs.

4. How long can a subroutine be written?

Note: The book first lists the research results on the impact of subroutine code length on quality over the years!

If you want to write a subroutine with more than 200 lines of code, you need to be careful. For subroutines with more than 200 lines of code, no research has found that it can reduce the cost or error rate, and after more than 200 lines, you will encounter problems in readability sooner or later.

* For details about function complexity, refer to another article.

High-quality subprogramsCheck List:

Overall situation

Is y/n well justified in creating subprograms?

Y/N has been put into a separate subroutine for all the parts suitable for separate proposal?

Is a strong and clear "Verb + object" phrase used in the Y/n process name? Does the function name describe its return value?

Does the name of the Y/n subprogram describe everything it does?

Does y/n create naming rules for common operations?

Is there a loose coupling between Y/n subprograms? Is the connection between subprograms and other subprograms small, clear, visible, and flexible )?

Is the length of the Y/n subroutine determined by its functions and logic, not by any human encoding standards?

Parameter transfer:

In Y/N, does the subprogram parameter table show a holistic and consistent interface abstraction?

Is the sorting order of Y/n subroutine parameters reasonable?
Is it consistent with the parameter arrangement sequence of similar subprograms?

Is the Y/n interface described in this document?

Does the number of Y/n subprograms not exceed 7?

Does y/N use each parameter?

Does y/n subprograms avoid using input parameters as working variables?

Y/n if the subroutine is a function, can it return a valid value in all possible circumstances?

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.