1. 条件判断概述
条件判断是编程中非常基础且重要的结构,它允许程序根据特定条件作出不同的执行路径选择。在实际开发中,良好的条件判断设计不仅能提升代码可读性,还能增强可维护性。
本章我们将重点讨论两个实践建议:
- 条件判断的封装
- 避免使用否定式条件判断
2. 条件判断结构
条件判断是程序逻辑分支的核心机制,它让程序能够根据不同布尔表达式的结果执行不同的代码块。
常见的条件判断结构包括:
if
语句if-else
语句else-if
语句链switch-case
(Java 中)- 三元运算符(Ternary Operator)
为了便于说明,本节使用类 Java 伪代码展示逻辑结构。
2.1 if 语句
if
是最基本的条件判断结构,当指定条件为 true
时,才会执行对应的代码块。
示例:
algorithm IfStatement(condition):
// INPUT
// condition = 布尔表达式
// OUTPUT
// 如果 condition 为 true,执行对应的代码块
if condition:
// 执行代码
2.2 if-else 语句
if-else
允许程序在条件为 true
或 false
时分别执行不同的代码块。
示例:
algorithm IfElseStatement(condition):
// INPUT
// condition = 布尔表达式
// OUTPUT
// 根据 condition 的值执行不同代码块
if condition:
// 条件为 true 时执行
else:
// 条件为 false 时执行
实际例子:
algorithm IfElseExample(country):
// INPUT
// country = 字符串类型,表示国家代码
// OUTPUT
// 将国家代码转换为完整名称,否则设为 "Unknown"
if country == "sk":
country = "Slovakia"
else:
country = "Unknown"
⚠️ 注意:在实际 Java 中,字符串比较应使用
equals()
方法,不要使用==
。
2.3 if-else-if 结构
该结构允许我们检查多个条件,并执行第一个满足条件的代码块。
示例:
algorithm IfElseIfStatement(condition1, condition2):
// INPUT
// condition1, condition2 = 布尔表达式
// OUTPUT
// 执行最先满足的条件对应的代码块
if condition1:
// condition1 为 true 时执行
else if condition2:
// condition1 为 false 且 condition2 为 true 时执行
else:
// 所有条件都不满足时执行
3. 条件判断的封装
封装条件判断是指将多个嵌套或重复的条件判断逻辑提取到一个方法或函数中,以提高代码的可读性和复用性。
3.1 未封装的写法
algorithm ConditionalsWithoutEncapsulation(customer_type, order_total):
// INPUT
// customer_type = 客户类型(如 'regular', 'premium')
// order_total = 订单总金额
// OUTPUT
// 根据客户类型和订单金额设置折扣
discount = 0
if customer_type == "regular":
if order_total > 100:
discount = 0.15
else if customer_type == "premium":
if order_total > 100:
discount = 0.2
else:
discount = 0.1
3.2 封装后的写法
将逻辑封装到一个函数中,提高复用性:
function getOrderDiscount(order_total, customer_type):
// INPUT
// order_total = 订单总金额
// customer_type = 客户类型
// OUTPUT
// 返回对应折扣率
discount = 0
if customer_type == "regular":
if order_total > 100:
discount = 0.15
else if customer_type == "premium":
if order_total > 100:
discount = 0.2
else:
discount = 0.1
return discount
✅ 优点:
- 避免重复代码
- 提高可维护性
- 逻辑集中,便于修改
❌ 反例:
如果多个地方都写类似的 if-else 判断,一旦需求变更,维护成本会很高。
4. 避免否定式条件判断
避免使用否定式条件判断是一种良好的编码习惯,它有助于提高代码的可读性和逻辑清晰度。
4.1 使用正向条件判断
使用正向条件(positive condition)比否定式更直观,例如:
algorithm PositiveConditionExample(x):
// INPUT
// x = 数值型变量
// OUTPUT
// 根据 x 的值执行不同逻辑
// 否定式 ❌
if x != 0:
// 执行操作
// 正向式 ✅
if x == 0:
// 执行操作
4.2 使用正向语言表达
使用正向词汇来描述判断逻辑,比如用 if success
而不是 if !error
。
algorithm PositiveLanguageExample(tall, short):
// INPUT
// tall, short = 布尔变量
// OUTPUT
// 根据变量值执行不同逻辑
// 否定式 ❌
if !tall:
// 执行操作
// 正向式 ✅
if short:
// 执行操作
4.3 反转逻辑以避免否定判断
有时候可以通过反转逻辑来避免使用 !
。
algorithm InvertLogicExample(x):
// INPUT
// x = 数值型变量
// OUTPUT
// 根据 x 的值执行不同逻辑
// 否定式 ❌
if !(x > 10):
// 执行操作
// 正向式 ✅
if x <= 10:
// 执行操作
✅ 好处:
- 更易理解,减少认知负担
- 降低逻辑错误风险
- 提高代码可维护性
5. 总结
条件判断是程序控制流的核心。通过以下两个实践可以显著提升代码质量:
- ✅ 封装条件判断逻辑:将复杂判断逻辑提取到独立方法中,提升复用性与可维护性
- ✅ 避免否定式判断:使用正向逻辑和正向语言,提高代码可读性
良好的条件判断结构不仅让代码更清晰,也更容易测试和调试,是写出高质量代码的关键一环。