Improved coding style

Source: Internet
Author: User

It should be said that many of us, programming history is not short, but many times, we do not have confidence in the code we have compiled, sometimes we are afraid of seeing it, although this code implements the required functions. The reason is that the Code is messy and aesthetic due to poor code style. The purpose of this article is to explain the general good style and Help Readers write "beautiful" code, note that the languages involved in this article include C, C ++, JAVA, and BASIC, I have used three languages, instead of just one, to show readers that the style is common to the language.

1) identifier (naming rule)

Identifiers should be intuitive and readable. They are expected to be informative. It is best to use English words or their combinations to facilitate memory and reading. Do not use Chinese pinyin for naming. Long names can better express meanings. Therefore, function names, variable names, and class names can contain up to a dozen characters, such:

Good name: int student_age, teacher_age;

Bad Name: int age1, age2;

But is the name longer the better? No, please refer to the following example:

Struct student

Int student_age;/* bad name */

Char * student_name;

Struct student

Int age;/* good name */

Char * name;

Why is the former poor? because many operators, student, the name of the struct, have already expressed

Student.

Another example is the string copy function void StringCopy (char * str1, char * str2 ).

Whether or not Chu copied str1 to str2. Yes

To make the parameter name more meaningful, such as strSource and trDestination. In this way, we can see from the name

Copy strSource to strDestination.

Single-character names are also useful, common such as I, j, k, m, n, x, y, z, and so on. They are usually used as functions

Variable.

2) operator priority

If there are many operators in the code line, use parentheses to determine the Operation Sequence of the expression. Avoid using the default

Priority. It is difficult to note the priority of operators,

Even if you are familiar with and use the code correctly, the written code is easy to produce ambiguity and make it less readable.

Good style if (a B) & (a & c ))

Bad style if (a B & a & c)

Although the latter has the same functions as the former, the latter is terrible and hard to read.

3) do not write complex compound expressions.

The use of compound expressions can make the code more concise when appropriate, but it cannot be complicated to understand.

For example:

Max = a> B? (A> c? A: c): (B> c? B: c) // The compound expression is too complex.

It should be changed:

Max =;

Max = B;

Max = c;

The preceding if statement is added only for one row because it complies with the "if, for, and while statements

There are many rules to be added, which can prevent writing errors,

When such statements are nested, you will know the benefits of doing so.

4) Comparison between various data types and zero values

In JAVA, for the flag of the Boolean variable, the comparison with the zero value (Note: Not 0) is naturally the if (flag

Integer variables should be replaced with "=" or "! = "Is directly compared with 0.

If (value = 0)

If (value! = 0)

Cannot be written

If (value) // you may misunderstand that value is a Boolean variable.

If (! Value)

The zero value of the pointer variable is NULL. Although the value of NULL is the same as that of 0, they have different meanings. For the pointer Variable p, the if statement for comparing it with the zero value is as follows:

If (p = NULL)

If (p! = NULL)

Do not write

If (p = 0) // It is easy to misunderstand that p is an integer variable.

If (p! = 0)

5) multi-layer if statement

Do not use the following structure:

If (condition1)

...

If (condition2)

...

If (condition3)

...

...

Replace it with the if-else-if structure:

If (condition1)

...

Else if (condition2)

...

Else if (condition3)

...

...

This structure is clear, and the former can easily lead to the fact that you do not know what to write.

You can use the switch statement to replace the nested if statement for multi-branch selection.

6) Improve Cycle Efficiency

For the string name, see the following loop:

For (I = 0; I <strlen (name); I ++) is much less efficient than the following loop:

N = strlen (name );

For (I = 0; I <n; I ++)

The latter only needs to calculate the name length once.

7) Use less and use the goto statement with caution.

The goto statement can jump from the multi-loop body or code heap to the outside, for example:

...

...

...

On error goto errorhandler;

Errorhandler:

...

This method is commonly used in Visual Basic.

8) Eliminate the number of devils

The devil's number, the constant without a name. If you read the English documents, they say magicdata. Some of our works translate it into "magic number ", I prefer to translate it into "Devil's number" because it is a "devil" that causes extremely poor code readability ".

If you write the following code in the program:

For (I = 0; I <100; I ++); for (I = 0; I <99; I ++ ); no one knows what 100 or 99 is.

Meaning, you may mean that 100 is the boundary of the range (the maximum value), so you should define it so that the readers of the code can understand what you mean:

# Define MAX 100/* macro constant of C language */

Const int MAX = 100; // const constant in C ++

For (I = 0; I <MAX; I ++); for (I = 0; I
In addition, if a constant is closely related to other constants, this relationship should be included in the definition, rather than some isolated values.

For example:

Const float RADIUS = 100;

Const float DIAMETER = RADIUS * 2;

9) function return value

The function name and return value type cannot conflict in semantics. The C standard library function getchar violates this rule.

For example:

Char c;

C = getchar ();

If (c = EOF)

According to the getchar name, it is natural to declare the variable c as the char type. But unfortunately, getch

Ar is indeed not a char type, but an int type. Its prototype is as follows:

Int getchar (void );

10) random pointer

The "wild pointer" refers to a random pointer. It is not a NULL pointer and is a pointer to the "junk" memory. Ye

Pointers are dangerous and often cause bugs. There are two main causes: first, pointer variables are not initialized. In C/C ++, any pointer variable is not automatically NULL when it is just created, and its default value is random. Therefore, the pointer variable should be initialized at the same time when it is created, either set the pointer to NULL or set it to direct to the legal memory. For example

Char * p = NULL;

Char * str = (char *) malloc (100 );

Second, after the pointer p is free or deleted, It is not set to NULL, which makes people mistakenly think p is a valid pointer.

I still have a lot to explain about the encoding style. Due to the length of this article, I will talk about it for the time being and hope it will help programmers.

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.