Dart空安全异常处理优化:代码不符合DRY原则求修正
Dart代码优化:遵循DRY原则与完善空安全及输入验证
核心优化思路
将重复的输入验证逻辑提取为通用工具函数,复用校验逻辑同时强化空安全与输入规则校验,彻底消除代码冗余。
通用工具函数(复用核心校验逻辑)
import 'dart:io'; /// 获取非空且满足自定义规则的字符串输入 String getValidStringInput(String prompt, bool Function(String) validator, [String? errorMessage]) { String? input; do { stdout.write(prompt); input = stdin.readLineSync(); // 校验空输入/空白输入 if (input == null || input.trim().isEmpty) { print(errorMessage ?? '输入不能为空,请重新输入!'); continue; } // 校验自定义规则 if (!validator(input.trim())) { print(errorMessage ?? '输入不符合要求,请重新输入!'); } } while (input == null || input.trim().isEmpty || !validator(input.trim())); return input.trim(); } /// 获取有效整数输入(支持自定义规则) int getValidIntInput(String prompt, bool Function(int) validator, [String? errorMessage]) { int? input; do { stdout.write(prompt); final String? rawInput = stdin.readLineSync(); // 校验空输入/空白输入 if (rawInput == null || rawInput.trim().isEmpty) { print(errorMessage ?? '输入不能为空,请重新输入!'); continue; } // 校验是否为有效整数 input = int.tryParse(rawInput.trim()); if (input == null) { print(errorMessage ?? '请输入有效的整数!'); continue; } // 校验自定义规则 if (!validator(input)) { print(errorMessage ?? '输入不符合要求,请重新输入!'); } } while (input == null || !validator(input)); return input; }
优化后的Exercise1
void Exercise1() { // 获取符合要求的姓名(非空且长度≥3) final String name = getValidStringInput( 'What is your name? ', (input) => input.length >= 3, '姓名不能为空且长度不能少于3个字符,请重新输入!', ); // 获取符合要求的年龄(非负整数) final int age = getValidIntInput( 'Hello $name, What is your age? ', (input) => !input.isNegative, '请输入有效的非负年龄!', ); // 计算到100岁的剩余年份 final int yearsToHundred = 100 - age; // 输出结果 print( '\nHey $name, you are $age years old now. \nYou will be 100 years old in another $yearsToHundred years. \nEnjoy your life to the fullest, Cheers!'); }
优化后的Exercise2
void Exercise2() { // 获取有效的整数输入(仅需确保是整数) final int num = getValidIntInput( 'Enter a number: ', (_) => true, '请输入有效的整数!', ); // 判断奇偶并输出 print(num.isEven ? 'Even' : 'Odd'); }
优化亮点
- 严格遵循DRY原则:所有输入验证逻辑复用通用函数,消除重复的do-while代码块
- 强化空安全:函数返回非空类型,无需处理nullable变量的额外判断
- 完善校验逻辑:
- 自动过滤输入中的空白字符,避免无效空白输入
- 覆盖空输入、格式错误、规则不符三类异常场景
- 支持自定义错误提示,提升交互体验
内容的提问来源于stack exchange,提问作者Nikash Deka
相关产品推荐
相关产品推荐

