High-quality subroutines

Source: Internet
Author: User
1. Justification for creating a subroutine 1.1. Reduced Complexity

You can use a subroutine to hide some information, which is not considered in the main program. If the internal loop level is too deep, it means that a new subroutine needs to be extracted from the subroutine, And the nested part is extracted to form an independent subroutine, which can reduce the complexity of the Internet subroutine.

1.2. 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 the intention of this Code.

If (node <> null) then

While (node. next <> null) do

Node = node. next

Leafname = node. name

End while

Else

Leafname = ""

End if

The following statement is easier to understand:

Leafname = getleafname (node)

1.3. Avoid code duplication 1.4. Support subclass

The number of new codes required to cover short and regular subprograms is less than that required to cover lengthy and messy subprograms. If you can keep the covered subprograms simple, then, when implementing the derived class, you will also reduce the chance of making mistakes.

1.5. Hide order

For example, to log on to a user, you must first determine whether the verification code is correct, and then determine whether the user name and password are correct. These two operations should be placed in two subprograms, how to ensure that one sub-program depends on whether another sub-program has been executed.

1.6. Improve portability

Subroutines can be used to isolate unportable parts of a program to clearly identify and isolate future transplantation work. unportable parts include hardware dependencies and operating system dependencies.

1.7. simplify complicated Boolean judgment

In order to understand the procedures of the program, it is usually not necessary to study the details of complex Boolean judgments. These judgments should be placed in functions to improve code readability and emphasize the importance of them.

1.8. Improved performance

By using subprograms, You can optimize the code in one place. The code is concentrated in one place, which makes it easier to find out which codes are less efficient to run.

Other reasons

Ø isolation complexity

Ø hide Implementation Details

Restrictions on the impact of changes

Ø hide global data

Forming Central Control Points

Facilitate reusable code

Achieve specific reconstruction goals

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

One of the biggest psychological barriers when writing effective subprograms is reluctant to write a simple subprogram for a simple purpose. Writing a subprogram with only two or three rows of data looks a little useless, however, experience can indicate that a very small subprogram is useful.

Improve readability

Simple operations are often complicated.

2. Design on subroutine

Cohesion refers to the closeness between various programs in a subroutine.

Feature cohesionIs the strongest and best cohesion, that is, let a sub-program execute only one operation. For example, subprograms such as sin () and getcustomername () are highly cohesive. Of course, to evaluate cohesion in this way, the premise is that the operations performed by the subroutine are consistent with their names.

Other types of cohesion are generally considered unsatisfactory.

Cohesion in orderIt refers to the operations that need to be performed according to a specific program in the subprogram package. The data needs to be shared, and a complete function is completed only after all the operations are completed. For example, a subroutine calculates the age and retirement time of an employee based on the given date of birth. If the subprogram calculates the age of an employee and then the retirement time based on the age, the subprogram has the cohesion in sequence. In this case, you can create two different subprograms that calculate the age and retirement time of employees based on the given date. The subprograms that calculate the retirement time can call the subprograms that calculate the age, in this way, both have functional cohesion.

Cohesion in CommunicationIt means that different operations in a sub-program use the same data, but there is no other connection. In the example above, the input date first calculates the age and then calculates the retirement time, the same birth date is used between two computations, so this subroutine only has cohesion in communication.

Temporary cohesionIt refers to some subprograms that need to be executed at the same time, such as startup () shutdown. The startup () subroutine may need to read the configuration file, initialize the temporary file, and set the Memory Manager. To make him the most effective, it should be the original temporary cohesion subroutine to call other subroutines, these word programs to complete specific operations, rather than directly by him to execute all the operations.

Logical cohesionA number of operations are put into the same subroutine, and an operation is selected to be executed using the passed execution mark.

Coincidence cohesionIt means that there is no visible association between operations of subprograms.

3. Guiding Principles

Describes all things performed by subprograms.

Avoid the use of meaningless fuzzy or ambiguous VerbsSome verbs have flexible meanings and can be extended to cover almost any meaning. Subprograms such as elastic mservices () and processinput () cannot describe what the program is doing. They can only describe what is related to the service and input.

Do not use numbers alone to form different subprogram namesFor example, write all the code into a large function, create a large function for every 15 lines of code, and name them part1 and part2 respectively.

Determine the length of the subroutine name as neededThe maximum length of the variable name is 9 to 15 characters.

When naming a function, you must describe the returned words,For example, customerid. next () is a good function name.

Add an object to a verb with a strong tone when naming a processFor example, printdocument () and check order infor () are both good process names. In object-oriented languages, you do not need to add the Object Name (object) to the process name, such as document (), orderinfo. check ().

Accurate use of opponent words,For example, add \ remove increment \ decrement open \ close

Begin \ end insert \ delete show \ hide

Creste \ destroy lock \ unlock source \ target

First \ last min \ max start \ stop

Get \ put next \ previous up \ down

Get \ set old \ new

4. How long can a subroutine be written?

Ensure functional cohesion, as short as possible

Ø no more than 200 rows. IBM research shows that the maintainability and error rate of subroutines with more than 200 rows will increase.

5. How to Use subroutine Parameters

Follow input-Modify-Output sequence ParametersModify: parameters used for both input and output in a timely manner, such as reference objects

If several subprograms use similar parameters to make the order of these parameters consistent. For example, the Append (array <Char> [] () [], Int32, Int32) and Insert (array <Char> [] () [], Int32, Int32) of stringbuilder)

Use all parameters

Put the status or error variable behind.State variables are generally enumeration types, such as Regex. Match (String, String, RegexOptions)

Do not use parameters of subprograms as working variables.

Error

Int Multiply (int multiplier)

{

Multiplier * = 2;

..........

Return multiplier

}

In the last line of code above, the value of multiplier has changed. If you want to modify this program in the future, use the original input value elsewhere, you may assume that multiplier is a parameter that contains the original input value and uses it, but not in fact.

Correct

Int Multiply (int multiplier)

{

Int product = 0;

Product = multiplier * 2;

.........

Return product;

}

Description of parameter assumptions in the interface ,Through comments or assertions, we will discuss how to write self-instruction code later.

Parameters are used for input, to be modified, and for output.

Unit of the number of parameters

Acceptable value range

Specific value that should not appear

The parameter is limited7Within It is related to the Memory Characteristics of people. It is difficult for people to remember information of more than 7 units at the same time.

Passing parameters or objects for the subroutine to maintain its interface Abstraction For example, if a program has 10 attributes, the called subroutine can operate on only three of them. Do we transmit only three pieces of data or the entire object? What kind of abstraction should be expressed by the subprogram interface is the key to its handling. If you find that you create an object first, enter the three data items of the called subroutine into the object. after calling the subroutine, you can retrieve the values of the three data items from the object, this indicates that you should pass only the three data items, rather than objects.

6. Special considerations when using functions

A function is a subroutine with a return value. A process is a subroutine with no return value.

Difference:

If (report. FormatOutput (formattedReport) = sussess) then

Good

Report. FormatOutput (formattedReport, out oupputStatus)

If (oupputStatus = success) then

 

Status = report. FormatOutput (formattedReport)

If (status = successe)

(

)

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.