【C&C++】- 如何合理减少if else 语句

实现简洁的if else语句

使用if else,有时间看起来会比较复杂,但这个可以通过在小块中进行编写代码来解决, 条件语句的使用增加了代码的可阅读性. 然而优先处理错误的情况是一条最佳实践 ,可以简化if else的逻辑,下面基于一个例子进行讲述.

例子 - 数据库的更新:

updateCache() - 它是一个基于类级别的变量来决策更新主数据库的方法.
updateBackupDb() - 一个更新数据的方法.

使用这种写法的if else语句很难拓展和调试已有的功能.
优化前:

// A simple method handling the data
// base operation related task
private void updateDb(boolean isForceUpdate) {

// isUpdateReady is class level
// variable
if (isUpdateReady) {

	// isForceUpdate is argument variable
	// and based on this inner blocks is
	// executed
	if (isForceUpdate) {

	// isSynchCompleted is also class
	// level variable, based on its
	// true/false updateDbMain is called
	// here updateBackupDb is called
	// in both the cases
		if (isSynchCompleted) {
			updateDbMain(true);
			updateBackupDb(true);

		} else {
			updateDbMain(false);
			updateBackupDb(true);
		}
	} else {

	// execute this if isUpdateReady is
	// false i. e., this is dependent on
	// if condition
		updateCache(!isCacheEnabled);

	// end of second isForceUpdate block
	}

	// end of first if block
}

// end of method
}

在上述的代码中,通过一个bool类型的变量通过if else和return语句将代码切为小块. 但上述代码主要实现的是
:

  1. 如果数据更新是没有ready的情况下,是不需要进入这个方法的,直接退出这个方法
  2. 类似地,当isForceUpdate 为false的情况下,那么执行else语句中的updateCache,然后return.
  3. 在最后一个一步中,当执行完其它的所有任务后,更新backup db和main db.

优化后:

// A simple method handling the
// data base operation related
// task
private void updateDb(boolean isForceUpdate) {

// If isUpdateReaday boolean is not
// true then return from this method,
// nothing was done in else block
if (!isUpdateReady)
	return;

// Now if isForceUpdate boolean is
// not true then only updating the
// cache otherwise this block was
// not called
if (!isForceUpdate) {
	updateCache(!isCacheEnabled);
	return;
}

// After all above condition is not
// full filled below code is executed
// this backup method was called two
// times thus calling only single time
updateBackupDb(true);

// main db is updated based on sync
// completed method
updateDbMain(isSynchCompleted ? true : false);
}

上述的代码主要是基于条件语句来考虑if else语句的优化, 这种类型的简单代码对于后续的开发者会比较容易的进行调试、理解、和功能扩展.

总结

优先处理错误的情况是一条最佳实践

参考链接:
writing-clean-else-statements

你可能感兴趣的:(C&C++,c++,内存优化,linux,freertos)