Using numeric literals instead of Month or DayOfWeek enum constants when working with Java’s java.time API
reduces code readability and can lead to errors.
The java.time API introduced in Java 8 provides two convenient enums: Month for months of the year and
DayOfWeek for days of the week. These enums make code more readable and self-documenting compared to numeric literals.
When you write LocalDate.of(2024, 1, 15), it’s not immediately clear whether the month parameter is zero-indexed (like the old
Calendar API) or one-indexed. A reader must either memorize the API or look it up. In contrast, LocalDate.of(2024, Month.JANUARY,
15) is unambiguous and instantly understandable.
Replace numeric literals in your code with their corresponding java.time.Month or java.time.DayOfWeek enum constants when
creating or manipulating dates. Most factory methods in the java.time API have overloads that accept enums instead of integers.
Use the following mapping to update your values:
| Value | Month | DayOfWeek |
|---|---|---|
|
1 |
|
|
|
2 |
|
|
|
3 |
|
|
|
4 |
|
|
|
5 |
|
|
|
6 |
|
|
|
7 |
|
|
|
8 |
|
- |
|
9 |
|
- |
|
10 |
|
- |
|
11 |
|
- |
|
12 |
|
- |
LocalDate date = LocalDate.of(2024, 1, 15); // Noncompliant; "1" is used to represent January YearMonth yearMonth = YearMonth.of(2024, 6); // Noncompliant; "6" is used to represent June
LocalDate date = LocalDate.now(ZoneOffset.UTC);
if (date.getMonthValue() == 9) { // Noncompliant; "9" is used to represent September
// Handle September
}
DayOfWeek today = LocalDate.now(ZoneId.of("Europe/Paris")).getDayOfWeek();
boolean isWeekend = today.getValue() == 6 || today.getValue() == 7; // Noncompliant; "6" and "7" are used to represent Saturday and Sunday
LocalDate date = LocalDate.of(2024, Month.JANUARY, 15); YearMonth yearMonth = YearMonth.of(2024, Month.JUNE);
LocalDate date = LocalDate.now(ZoneOffset.UTC);
if (date.getMonth() == Month.SEPTEMBER) {
// Handle September
}
DayOfWeek today = LocalDate.now(ZoneId.of("Europe/Paris")).getDayOfWeek();
boolean isWeekend = today == DayOfWeek.SATURDAY || today == DayOfWeek.SUNDAY;