Aijan@programming.dev to Programming@programming.dev · 2 months agoAvoiding if-else Hell: The Functional Stylelackofimagination.orgexternal-linkmessage-square35fedilinkarrow-up195arrow-down18
arrow-up187arrow-down1external-linkAvoiding if-else Hell: The Functional Stylelackofimagination.orgAijan@programming.dev to Programming@programming.dev · 2 months agomessage-square35fedilink
minus-squareKissaki@programming.devlinkfedilinkEnglisharrow-up10arrow-down1·edit-22 months agoUsing early returns and ternary conditional operator changes private boolean meetsRiderPreferences(Rider rider, Driver driver) { if (driver.rating >= 4.5) { if (rider.preferences.includes('Premium Driver')) { return driver.isPremiumDriver; } else { return true; } } else if (driver.rating >= 4.0) { return true; } else { return false; } } to private boolean meetsRiderPreferences(Rider rider, Driver driver) { if (driver.rating < 4.0) return false; if (driver.rating < 4.5) return true; return rider.preferences.includes('Premium Driver') ? driver.isPremiumDriver : true; } dunno if java has them, but in C# switch expressions could put more of a case focus on the cases private boolean meetsRiderPreferences(Rider rider, Driver driver) { return driver.rating switch { < 4.0 => false, < 4.5 => true, _ => rider.preferences.includes('Premium Driver') ? driver.isPremiumDriver : true, }; } or with a body expression private boolean meetsRiderPreferences(Rider rider, Driver driver) => driver.rating switch { < 4.0 => false, < 4.5 => true, _ => rider.preferences.includes('Premium Driver') ? driver.isPremiumDriver : true, }; The conditional has a true result so it can be converted to a simple bool condition as well. private boolean meetsRiderPreferences(Rider rider, Driver driver) => driver.rating switch { < 4.0 => false, < 4.5 => true, _ => !rider.preferences.includes('Premium Driver') || driver.isPremiumDriver, };
Using early returns and ternary conditional operator changes
private boolean meetsRiderPreferences(Rider rider, Driver driver) { if (driver.rating >= 4.5) { if (rider.preferences.includes('Premium Driver')) { return driver.isPremiumDriver; } else { return true; } } else if (driver.rating >= 4.0) { return true; } else { return false; } }
to
private boolean meetsRiderPreferences(Rider rider, Driver driver) { if (driver.rating < 4.0) return false; if (driver.rating < 4.5) return true; return rider.preferences.includes('Premium Driver') ? driver.isPremiumDriver : true; }
dunno if java has them, but in C# switch expressions could put more of a case focus on the cases
or with a body expression
The conditional has a true result so it can be converted to a simple bool condition as well.