Java Switch多变量优化:英国车牌年份设置代码改进需求
Hey there! Your instinct that the current code can be improved is spot-on—let's walk through a cleaner, more maintainable solution that fixes bugs and cuts out all that messy hardcoding. First, let's break down what's off with the existing implementation, then build something better.
What's Wrong With the Current Code?
Let's start with the pain points:
- Manual string parsing: Cutting up the date string with
substringis error-prone. If the date format ever changes (e.g., using slashes instead of hyphens), the code breaks instantly. - Hardcoded year checks: The long list of
if-elsestatements means you have to update the code every year, and it's easy to make mistakes (like the duplicateyear.equals("18")check in your code—one maps to 19, the other to 67, which is a bug!). - Redundant switch cases: Grouping months with
casestatements works, but checking month ranges directly is simpler and easier to read.
The Clean, Maintainable Solution
First, let's use Java's built-in LocalDate class to handle date logic safely—no more manual string slicing. Then we'll implement the UK license plate rules directly, without hardcoding every year:
Key UK License Plate Rules (From Your Requirements)
- March 1 to August 31: Use the last two digits of the current year (e.g., 2017 → "17")
- September 1 to February 28/29: Use the last two digits of the preceding year plus 50 (e.g., 2017 September → 17 + 50 = "67"; 2018 February → 17 + 50 = "67")
Optimized Code
import java.time.LocalDate; public void setVehiclePlateYear(StartDate startDate) { // Parse the date string into a proper LocalDate object (safe, no manual slicing!) LocalDate date = LocalDate.parse(startDate.getStartDateString()); int year = date.getYear(); int month = date.getMonthValue(); String vehiclePlateYear; if (month >= 3 && month <= 8) { // First half of the year: use last two digits of current year vehiclePlateYear = String.format("%02d", year % 100); } else { // Second half (Sep-Feb): use last two digits of the preceding year + 50 int baseYear = (month <= 2) ? (year - 1) : year; vehiclePlateYear = String.format("%02d", (baseYear % 100) + 50); } setPlateDate(vehiclePlateYear); }
Why This Works Better
- Safe date handling:
LocalDateparses standard ISO dates (like "2017-06-17") automatically, and throws a clear error if the date is invalid—no more silent failures from bad substring cuts. - No hardcoding: This logic works for any year, not just the ones listed. You'll never have to add another
ifstatement when a new year rolls around. - Clear logic: Anyone reading the code can immediately see the split between first/second half of the year, and how the plate year is calculated.
- Bug-free: Fixes the duplicate year check and incorrect mappings in your original code.
Optional: Lambda Expression Version (If You're Curious)
You mentioned you're not familiar with Lambdas, so this is totally optional—but here's how you could wrap the logic in a Lambda for reusability:
import java.time.LocalDate; import java.util.function.Function; // Define the calculation as a reusable function Function<LocalDate, String> calculatePlateYear = date -> { int year = date.getYear(); int month = date.getMonthValue(); return (month >= 3 && month <= 8) ? String.format("%02d", year % 100) : String.format("%02d", ((month <= 2 ? year - 1 : year) % 100) + 50); }; // Use it in your method public void setVehiclePlateYear(StartDate startDate) { LocalDate date = LocalDate.parse(startDate.getStartDateString()); String vehiclePlateYear = calculatePlateYear.apply(date); setPlateDate(vehiclePlateYear); }
This is just a more compact way to write the same logic—stick with the first version if you find it easier to read!
内容的提问来源于stack exchange,提问作者Steerpike

