Improve code quality: how to write functions

Source: Internet
Author: User

Read Catalogue

    • Named
    • function parameters
    • Writing the function body
    • Summarize

function is the most basic unit of implementing program function, each program is composed of one of the most basic functions. Writing a function is one of the most critical steps in improving program code quality. This paper discusses how to write a function that is readable, easy to maintain and easy to test, from the aspects of function naming, code distribution, and skill.

Go back to the top of the name

First of all, naming is the first step to improving readability. How to name variables and functions has always been one of the pain points in the developer's heart, and it's even harder for us to speak to non-English speakers. Let me say some thoughts and feelings about how to name a function:

Adopt a Uniform naming convention

Before talking about how to take an accurate and elegant name for a function, the first and foremost thing to do is to have a uniform naming convention. This is the most basic guideline for improving code readability.
Pascal's nomenclature and Hump nomenclature are two popular rules at present, and the rules used in different languages may not be the same, but one thing to keep in mind: keeping the team and personal style consistent.
1. Pascal's name Law
The Pascal nomenclature is simply that: when multiple words form a name, the first letter of each word is capitalized. Like what:

1 public void SendMessage (), 2 public void Calculateprice ();

In C #, this nomenclature is commonly used in classes, properties, functions, and so on, and in JS, constructors are also recommended to be named in this way.

2, Hump name law
The hump naming method is similar to the Pascal nomenclature, when multiple words form a name, the first word is all lowercase and the first letter of the following word is capitalized. Like what:

1 var sendMessage = function () {};2 var calculateprice = function () {};

Hump nomenclature is generally used for fields, local variables, function parameters, and so on. , in JS, the function is also used to name this method.

What kind of naming convention to adopt is not absolute, the most important thing is to abide by the team contract, language specification.

Describe everything that a function does as completely as possible

Some developers may feel that short function names may seem more concise and more comfortable than raised here functions. But in general, the shorter the function name, the more abstract the meaning of the description is. The first impression that a function user has on a function is the function name, and then we should describe as much as possible what the function does, to prevent the user from knowing or misunderstanding the potential error.
For example, suppose we do a comment adding function, add it and return the total number of comments, how to name it more appropriate?

1//Description not complete function Name 2 var count = function addcomment () {};3 4//Description full function name 5 var count = function Addcommentandreturncount () {};

This is just a simple example, the actual development may encounter more complex situations, the single responsibility principle is our development function to abide by the guidelines, but sometimes do not do the function of a single duty, remember that the function name should be as much as possible to describe everything. When you cannot name a function, you should analyze whether the function is written scientifically, and what can be done to optimize it.

Use accurate descriptive verbs.

This is a difficult point for native speakers of non-English, and to improve their ability to do so, the main thing is to improve their vocabulary and read more about good code accumulation experience.
Here is a brief talk about some of my own thoughts and views:
1, do not use too abstract a wide range of words
Many developers use a broad verb to name a function, and the most typical example of this is the word get. We usually develop in a variety of ways to get the data, but every way with get is a little too abstract. Specifically how to name, to be specific analysis:
(1) Simple return data

1 Person.prototype.getFullName = function () {2     return this.firstname = this.lastname;3}

(2) Obtaining data from remote

1 var fetchpersons = function () {2     ... 3     $.ajax ({4     }) 5}

(3) Loading data from local storage

1 var loadpersons = function () {};

(4) Obtaining data by calculation

1 var calculatetotal = function () {};

(5) Finding data from an array

1 var findsth = function (arr) {};

(6) generating or obtaining from some data

1 var createsth = function (data) {};2 var buildsth = function (data) {};3 var parsesth = function (data) {};

This is a simple example, we usually encountered in the development of the situation will certainly be much more complex, the key is to rely on the accumulation of words, read more excellent source

Here are some of the commonly used antithesis words, you can refer to the use of

1 add/remove        increment/decrement       open/close2 begin/end            insert/delete                      show/hide3 create/destory    lock/unlock                        source/target4 first/last              min/max                             star/stop5 get/put                next/previous                     Up/down     6 Get/set                old/new
Establish naming conventions based on different projects and requirements.

This is also important, especially in team work, where different projects and requirements may lead to different naming conventions.
For example, we usually use the naming convention is the dynamic structure, that is, the verb in front, after the noun disaster. But some projects, such as data interfaces, have teams that use names before, verbs in the latter form, for example:

1 public static product[] Productsget () {};2 public static product[] Productsdel () {};3 public static customer[] Customerdel () {};4 public static customer[] Customerdel () {};

The advantage of this is to see the previous noun, such as productsget, can quickly know that this is a product-related data interface.
Of course this is not absolute, the key is to team together to develop and abide by the same set of naming rules.

Back to top function parameters

The function user must strictly abide by the parameters of the function definition when calling the function, which is very important to the usability and testability of the function. I'll talk about some ideas on how to optimize function parameters in several ways.

Number of parameters

There is no doubt that the more function parameters, the less ease of use of the function, because the user needs to strictly view the parameter list in order to enter parameters, if a parameter is wrong, it will lead to unpredictable results.
However, the less the function parameter, the better? Let's take a look at the following example:

1 var count = 0;2 var UnitPrice = 1.5;3 .... 4 ... 5 var calculateprice = function () {6     return count * unitprice;7}

In this example, we calculate the price by calculateprice this function, the function does not receive any parameters, and is calculated directly from the two global variables UnitPrice and count. The definition of this function is very convenient for the user and can be called directly without having to enter any parameters. However, there may be potential bugs: Global variables may be modified elsewhere, difficult to unit test, and so on. So, this function can pass in quantity and price information:

1 var calculateprice = function (count, UnitPrice) {2     return count * unitprice;3}

In this way, when the function consumer is in use, it is necessary to pass in the parameter to make the call, avoiding the problem that the global variable may exist. It also reduces coupling, improves testability, and does not have to rely on global variables when testing.

Of course, in cases where the function is not dependent on global variables and testability, the less the function parameter, the better. In the Code encyclopedia, the parameters of the function are limited to 7 or less, which can be used as our reference.
Sometimes, we inevitably use more than 10 functions, in which case we can consider constructing similar parameters into a class, so let's take a look at a typical example.
I believe that we usually do such a function, list filtering, which involves a variety of conditions of filtering, sorting, paging and so on, if the parameters are listed in one place will certainly be very long, for example:

1 var filterhotel = function (city, CheckIn, CheckOut, Price, star, position, WiFi, meal, sort, pageIndex) {}

This is a filter hotel function, where the parameters are the city, check-in and check-out time, price, star, location, whether there is WiFi, whether there is breakfast, sorting, page numbers and so on, the actual situation may be more. In this particular case, we can consider extracting some of the similar parameters into a class:

1 function dateplace (city, CheckIn, CheckOut) {2     this.city = city; 3     this.checkin = checkIn; 4     this.checkout = CheckOut 5} 6  7 function hotelfeature (price, star, position, WiFi, meal) {8     this.price = Price; 9     This.sta r = star;10     this.position = position;11     This.wifi = wifi;12     this.meal = meal;13}14 var Filterhotel = funct Ion (Dateplce, hotelfeature, Sort, pageIndex) {};

Extracting multiple parameters into an object, although the number of objects increased, but the function parameters are clearer, the call is more convenient.

Try not to use the bool type as a parameter

Sometimes we write a case where bool is used as a parameter, such as:

1 var getproduct = function (finished) {2     if (finished) {3     }4     else{5     }6}7 8//Call 9 GetProduct (TRUE);

If there is no comment, the user sees the code: GetProduct (True), he must not know what the meaning of true is, but also to see the function definition in order to understand how the function is used. This means that the function is not clear enough and should be considered to optimize it. There are usually two ways to optimize it:
(1) Divide the function into two, divided into two functions getfinishedproduct and getunfinishedproduct
(2) converting bool to a meaningful enumeration getproduct (Productstatus)

Do not modify input parameters

If an input parameter is modified within a function, it is likely to cause a potential bug, and the user does not know that the function parameter will be modified after the function is called.
The proper use of input parameters should be to only pass in parameters for function calls.
If modifications are unavoidable, be sure to explain them in the comments.

Try not to use output parameters

Use the output parameters to illustrate that this function does not only do one thing, but also that users may be confused when they use it. The right way to do this is to decompose the function so that the function does only one thing.

Back to top write function body

function body is the whole logic that realizes function function, it is the key place of a function. Let me talk about some of the personal ideas about the writing of the function code.

Related actions are put together

Sometimes, we do a series of operations within a function to complete a function, such as:

1 var calculatetotalprice = function ()  {2     var roomcount = Getroomcount (); 3     var mealcount = Getmealcount (); 4 5     var roomprice = Getroomprice (Roomcount), 6     var mealprice = Getmealprice (Mealcount), 7 8     return Roomprice + MEALPRICE;9}

This code calculates the room price and the breakfast price, and then adds the two together to return the total price.
This code at first glance, there is no problem, but we analyze the code, we first obtained the number of rooms and the number of breakfast, and then the number of rooms and breakfast to calculate the price of the two separately. In this case, the number of rooms and the code for calculating the room price are scattered in two locations, and the breakfast price is distributed to two locations. That is, the two-part code is scattered around so that the logic of reading the code is slightly irrelevant and the code is not well organized. We should let the relevant statements and actions be put together, also conducive to refactoring code. We revise as follows:

1 var calculatetotalprice = function ()  {2     var roomcount = Getroomcount (); 3     var roomprice = Getroomprice ( Roomcount); 4 5     var mealcount = Getmealcount (); 6     var mealprice = Getmealprice (Mealcount); 7 8     return Roomprice + mealprice;9}

We put the relevant actions together so that the code looks clearer and easier to refactor.

Minimizing code nesting

We usually write if,switch or for statements are often the case, also must have written multi-layer if or for statement nesting cases, if the code nested more than 3 layers, it will be very difficult to read. We should try to avoid nesting multiple layers of code, preferably not more than 2 levels. Let me tell you about my usual techniques or methods of reducing nesting.

An If statement nesting problem

Multi-layer If statement nesting is often the case, what is the best way to reduce nesting?
1. Terminating functions or returning data as early as possible
If a function can be terminated directly if a condition is met, the condition should be placed first. Let's take a look at the following example.

1 if (condition1) {2     if (condition2) {3         if (condition3) {4         } 5         else{6             return; 7         }     8     } 9     else{10         return;11     }    }13 else {     return;15}

The IF statement in this code is nested in Layer 3, it seems to be very complex, we can extract the last return to the front.

1 if (!condition1) {2     return; 3} 4 if (!condition2) {5     return; 6} 7 if (!condition3) {8     return; 9}10//dosth

In this code, we extract the statement condition1 equals false to the front, terminate the function directly, and make the multi-layer nested IF statement the only one-layer if statement, and the code is clearer.

Note: In general, we write an if statement that writes the condition to true in the previous case, which is more in line with our thinking habits. If it is a multi-layered nesting situation, the nesting of if statements should be reduced first

2. If statement or switch statement is not applicable
Conditional statements are generally unavoidable, sometimes we have to judge a lot of conditions will write many If-elseif statements, nested words, it is more troublesome. If a new demand is added one day, we are going to add an IF branch statement, which is not only cumbersome but also error prone. The table-driven method proposed by the Code encyclopedia can effectively solve the problems caused by the IF statement. Let's look at the following example:

1 if (condition = = "Case1") {2     return 1; 3} 4 elseif (condition = = "Case2") {5     return 2; 6} 7 elseif (condition = = "Case3") {8     return 3; 9}10 elseif (condition = = "Case4") {One     return 4;12}

This code in turn to determine the four cases, if we add another situation, we will have to add another if branch, which may create a potential problem, how to optimize this code? We can use a map or dictionary to match each case to a corresponding value of one by one.

1 var map = {2     "case1": 1,3     "Case2": 2,4     "CASE3": 3,5     "Case4":}7 return map[condition];

With map optimization, the entire code is not only more concise, but also easier to modify and not easy to make mistakes.
Of course, many times our conditional judgment statement is not so simple, it may involve complex logic operations, you can see the code Daquan 18th, which has a detailed introduction.

3, extract inner layer nested as a function to call
When multiple layers are nested, we can also extract the inner nesting into a new function, and then call the function, so that the code is clearer.

For loop nesting optimizations

The For loop nesting is more complicated than if nesting, which is more cumbersome to read, and here are a few things to be careful about:
1, up to two tiers for loop nesting
2, the extraction of the inner layer loop into the new function
3, multi-layer cycle, do not simply status index variable named I,j,k, etc., easy to cause confusion, to have specific meaning

Extracting complex logic and semantics

Sometimes, we will write some more complex logic, reading the code of the people may not understand what to do, this time, should be extracted from this complex logic code.

1 if (age > Gender && = = "Man") {2     //dosth3}

This code means that when the age is greater than 18 and is male, it can be dosth, but it is still not clear enough to extract it.

1 var candosth = function (age, gender) {2     return > && gender = ' man '; 3}4 ... 5 ... 6 ... 7 if (Candosth (age, gender)) {8     //dosth9}

Although there is a function, the code is clearer and more semantic.

Back to top of the summary

In this paper, we talk about how to write the good one function from the three aspects of function naming, function parameter and function code writing. The article mentions a lot of specific situations, of course, the daily coding will certainly encounter more complex situations may I temporarily did not think. I briefly summed up a few points:
1. Name the variables and functions accurately
2, do not have the code of repetitive logic
3, the function of the number of rows not more than 20 lines, where the 20 line is just a ballpark, and not necessarily the number
4. Reduce nesting
I believe that we will have a lot of experience in this area, welcome to communicate and improve the quality of code together.

This article address: http://luopq.com/2016/02/21/write-good-function/, reprint

Improve code quality: how to write 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.