General control issues

Boolean expression

Use True and False to make Boolean judgments:
to represent the result of a Boolean expression. If the language used does not support this type, use a predefined macro or global variable to create one. Use implicitly to compare Boolean values ​​with true and false: while(a>b) instead of while((a>b)==true) to
simplify complex expressions
1. Split complex judgments and introduce new Boolean types Variable
2. Use complex expressions as boolean functions: If the test conditions are frequently used repeatedly or scattered, write this part of the code as a function, so that when reading the main process code, there is no need to read any complicated judgments; And the new function name program introduces an abstraction, which can clearly explain the purpose of the logical judgment in the code.
3. Use decision tables instead of complex conditions to
write positive form Boolean expressions.
1. In the if statement, convert the condition from the negative form to the positive form, and then swap the code following the if and else statements.

if(!statusOk){
	//do something
}else{
	//do something
}
改写成:
if(statusOk){
	//do something
}else{
	//do something
}

2. Use Di Morgan's theorem to simplify the negative Boolean judgment:

if(!displayOk || !printerOk)
改写成
if(!(displayOk && printerOk))

Di Morgan's theorem logic conversion rule:
Insert picture description here
use parentheses to make Boolean expressions clearer

if ( a< b = = c = =d )改写成if((a<b)= =(c= =d))…

All Boolean expressions are enclosed in parentheses to enhance the readability of the code. A simple counting technique is used to make the parentheses symmetrical: set "0" at the beginning. Follow the expression from left to right, when you encounter an open parenthesis and set it to "1", each time you encounter an open parenthesis, increase the number by 1, and every time you encounter a closing parenthesis, decrease the number by 1, if the final number returns to "0" , The number of brackets is balanced.
Insert picture description here
Understand how Boolean expressions are evaluated

利用短路求值判断:
if ( (denominator != 0) && ((item/denominator) > MIN_VALUE) )  

When denominator is equal to 0, the whole expression calculation will be divided by 0 error. But since the second part is calculated when the first part is true (not equal to 0), there will be no division by zero in Denominator, and there will be no division by zero error. If & becomes &&, a division by zero operation will occur
. Write numerical expressions
in the order of the number axis. Organize the number operations in the order of the number axis, and place i at the position after the judgment is successful, as in the following example:

MinElmts <= i and i<= MaxElmts	//判断i在最小值和最大值之间,所以就放在中间
i < MinElmts or MaxElmts < i			//判断i是否在两端,所以放在两边
while(i<inElmts)							//判断i小于inElmts,所以放在左边
while(minElmts<i)						//判断i大于minElmts

Guidelines for comparison with 0

while(!done)		//只有逻辑变量才使用隐式的比较
while( balance != 0)					//把数和0进行比较的正确方式,不要使用隐式比较
while( *charPtr != '\0')				//比较字符的格式
while( bufferePtr != NULL) 		//把指针和NULL进行比较

Common problems with boolean expressions.
The constant should be written on the left side of the equal sign, and the judged variable should be written on the right side of the compiler to prevent the situation where'==' is written as'='

Compound statement (statement block)

A'compound sentence' or'sentence block' refers to a group of sentences, which is regarded as a single sentence, used to control the flow of the program: (1) Write the parentheses together (2) Use the parentheses to express the condition clearly , Even one sentence needs to add a code block {}

Empty statement

1. Be careful to use empty statements: semicolon on a line, indent, add empty brackets
2. Create a DoNothing() preprocessor or inline function for empty statements
3. Try not to use non-empty loops

Tame dangerous deep nesting

Avoid using 3 to 4 levels of nesting. Here are some methods to avoid deep nesting:
1. Simplify nested if statements by repeating a certain part of the detection condition:

糟糕的深层嵌套代码:
if(Error==None) {
	/*lots of code*/
	if( PrinterRoutine!= NULL){
	/*lots of code*/
		if(SetupPage()){
		/*lots of code*/
				if(AllocMem(&PrintData)){
				/*lots of code*/
				}/* if AllocMem()*/
		}/* if SetupPage()*/
	}/* if PrinterRountine*/
}/* if Error * /
利用重复检测的非嵌套代码:
if( Error==None){ 
	/*lots of code*/
	if( PrinterRoutine!= NULL){
		/*lots of code*/
	}
}
if(Error== None && PrinterRoutine!= NULL && SetupPage()){
	/*lots of code*/ 
	if(AllocMem(&PrintData)){
	/*lots of code*/ 
	}
}

2. Use break block to simplify nested if

优化之后代码:
do{
	if(Error!=None) 
		break;
	/*lots of code*/
	if( PrinterRoutine!= NULL)
		break;
	/*lots of code*/
	if(SetupPage())
		break;
	/*lots of code*/
	if(AllocMem(&PrintData))
		break;
	/*lots of code*/
}while(false)

3. Convert the nested if into a set of i-then-else statements

茂盛的决策树:
if(10<quantity){
	if(100<quantity){
		if(1000<quantity){
			discount = 0.10;
		}else{
			discount = 0.05;
		}
	}else{
		discount = 0.025;
	}
}else{
	discount = 0.0;
}
将嵌套的if语句转换为一组if-then-else语句:
if(1000<quantity){
	discount = 0.10;
}else if(100<quantity){
	discount = 0.05;
}else if(10<quantity){
	discount = 0.025;
}else{
	discount = 0.0;
}

4. Convert the nested if into a case statement: Use if-else if-else to judge integers.
5. Extract the deeply nested code and put it into a subroutine. The new subroutine is just extracted from the original subroutine. Come out and form a new subroutine. Simplify the nesting of original subroutines. Transfer the nesting to the subroutine to make it easier to read the code.

The technical summary of reducing the nesting level:
(1) Re-interpret a part of the code.
(2) Convert to if-then-else
(3) Use break to simplify nested if
(4) Convert to case statement
(5) Extract deeply nested code into a separate subroutine
(6) Add intermediate state rewriting Code
(7) completely rewrite the deeply nested code

Programming basics: structured programming

The core of structured programming is based on the simple idea that a program is always a single-in-single-out structure, that is, a code block that can only start from one place and can only exit from one place, and there are no other imports and exports. The single-in-single-out control structure refers to a code block, which can only be executed from one position and can only end in one position.
The central argument of structured programming is that any kind of control flow can be generated by three structures: sequence, choice (if), and iteration (loop). When using break, continue, and return, we must adopt a critical attitude.

Control structure and complexity

How to measure complexity:
Insert picture description here

if (( ( Status = Success ) and Done ) or  (not Done and ( NumLines >= MaxLines)) ) then…
在这个程序中,从 1 算起,遇到“if”得 2,遇到“and”得 3,遇到“or”得 4,又遇到一个“and”得 5,这样程序总共含有 5 个决定点

How to deal with the ude measurement result of complexity:
0~5 The program may be good
6~10 You have to find a way to simplify the program
10 Above, you have to write part of the code as a subroutine and call it in the original program

Key points

1. Using Boolean expressions is simple and readable, which will greatly help improve the quality of your code.
2. Deep nesting makes the program difficult to understand. Fortunately, it can be avoided relatively easily.
3. Structured programming is a simple and still applicable idea: you can combine sequence, selection, and loop to develop any program.
4. Reducing complexity to the lowest level is the key to programming high-quality code.

Guess you like

Origin blog.csdn.net/weixin_37921201/article/details/88832124