Consolidate Conditional Expression Dart: One Check
Consolidate conditional expression in Dart means this: several different checks, one identical result, one named check instead. The Fowler mechanics plus the Dart 3 records-and-patterns version.
Consolidate conditional expression in Dart: when several different conditionals produce the *same* result, join them into one expression and extract it into a well-named method โ so the code says *why* the check exists instead of repeating *what* it checks. In Dart 3, records and switch expressions make the "one check" even cleaner. ๐ฌ Watch: consolidate conditional expression Watch a refactoring lecture walkthrough โ including the segment on consolidating conditionals โ then apply it to the Dart examples below. TBD โฑ TBD ยท Unknown โ click to play inline, or watch on YouTube . Minimal working example: consolidate conditional expression Dart You see this shape everywhere: a sequence of different checks, each leading to the identical result. Fowler's rule โ "multiple conditionals that lead to the same result or action" โ is the trigger. Before โ three checks, same result, reader has to notice the pattern: double discountRate({ required int loyaltyYears, required bool isStudent, required bool hasCoupon, }) { if (loyaltyYears >= 5) return 0.20; if (isStudent) return 0.20; if (hasCoupon) return 0.20; return 0.0; } After โ one check, one place, with a name that explains the *why*: double discountRate({ required int loyaltyYears, required bool isStudent, required bool hasCoupon, }) { if (isDiscountEligible( loyaltyYears: loyaltyYears, isStudent: isStudent, hasCoupon: hasCoupon, )) { return 0.20; } return 0.0; } bool isDiscountEligible({ required int loyaltyYears, required bool isStudent, required bool hasCoupon, }) { return loyaltyYears >= 5 || isStudent || hasCoupon; } The mechanics, straight from Fowler: (1) check none of the conditionals has side effects; (2) join them with logical operators โ consecutive same-result checks join with || , nested checks join with && ;โฆ