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

本文探讨了如何通过优先处理错误情况优化ifelse语句,以提升代码的可读性和可维护性。以数据库更新为例,展示了如何重构代码,使其更简洁。在优化后的代码中,首先检查是否需要更新,然后处理非强制更新情况,最后更新备份数据库。这种方法减少了重复代码,增强了逻辑清晰度,便于后续开发者理解和扩展。
摘要由CSDN通过智能技术生成
实现简洁的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值