DR Planning Tool Kotlin
👤 Sharing: AI
```kotlin
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.*
/**
* A simple Disaster Recovery (DR) Planning Tool.
* This tool helps determine the next practice DR test date based on
* predefined rules (e.g., must be a Wednesday, cannot be in the
* current month). It also handles specifying a blacklist of dates.
*/
fun main() {
val currentDate = LocalDate.now()
val targetDayOfWeek = DayOfWeek.WEDNESDAY // DR tests are on Wednesdays
val blacklist = mutableSetOf<LocalDate>() // Dates to avoid (e.g., holidays)
// Example Blacklist: Add dates for upcoming holidays. Format is YYYY-MM-DD.
blacklist.add(LocalDate.parse("2024-12-25")) // Christmas
blacklist.add(LocalDate.parse("2025-01-01")) // New Years
println("DR Planning Tool")
println("------------------")
println("Current Date: ${currentDate.format(DateTimeFormatter.ISO_DATE)}")
println("Target Day: ${targetDayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault())}")
println("Blacklisted Dates: ${blacklist.map { it.format(DateTimeFormatter.ISO_DATE) }}")
val nextDRTestDate = findNextDRTestDate(currentDate, targetDayOfWeek, blacklist)
if (nextDRTestDate != null) {
println("Next DR Test Date: ${nextDRTestDate.format(DateTimeFormatter.ISO_DATE)} (${nextDRTestDate.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault())})")
} else {
println("Could not find a suitable DR Test date. Check constraints and blacklist.")
}
}
/**
* Finds the next suitable date for a DR test, considering the target day of the week and blacklist.
*
* @param startDate The date to start searching from.
* @param targetDayOfWeek The desired day of the week for the DR test.
* @param blacklist A set of dates to exclude.
* @param maxAttempts Maximum number of days to search. Avoids infinite loops if no suitable date exists.
* @return The next suitable DR test date, or null if none is found.
*/
fun findNextDRTestDate(startDate: LocalDate, targetDayOfWeek: DayOfWeek, blacklist: Set<LocalDate>, maxAttempts: Int = 365): LocalDate? {
var currentDate = startDate.plusDays(1) // Start searching from tomorrow
var attempts = 0
while (attempts < maxAttempts) {
attempts++
// Rule 1: Must be the target day of the week
if (currentDate.dayOfWeek == targetDayOfWeek) {
// Rule 2: Cannot be in the current month (for this example constraint)
if (currentDate.month != startDate.month) {
//Rule 3: Must not be on the blacklist
if (!blacklist.contains(currentDate)) {
return currentDate // Found a suitable date!
}
}
}
currentDate = currentDate.plusDays(1) // Check the next day
}
// If we reach the maximum number of attempts, return null (no date found).
return null
}
```
Key improvements and explanations:
* **Clearer Structure:** The code is organized into functions for better readability and maintainability. The `main` function is focused on setting up and running the DR planning tool. The core logic for finding the date is in `findNextDRTestDate`.
* **`findNextDRTestDate` Function:**
* Takes `startDate`, `targetDayOfWeek`, and `blacklist` as parameters, making it more reusable.
* Includes a `maxAttempts` parameter to prevent infinite loops if no suitable date can be found. This is *essential* for robust code.
* Uses a `while` loop with a counter to control the search. This makes the logic much clearer than recursion for this type of problem.
* Starts the search from *tomorrow* using `startDate.plusDays(1)` to adhere to the implied requirement of not scheduling in the current day.
* **Explicit Rule Handling:** Clearly separates the checks for each rule using `if` statements, making the logic easy to understand and modify. Comments explain each rule.
* **Blacklist Check:** Correctly checks if the date is present in the blacklist using `!blacklist.contains(currentDate)`.
* **Return `null`:** Returns `null` if no suitable date is found, indicating that the tool couldn't find a date meeting the constraints. This is a much better approach than throwing an exception, as it allows the calling code to handle the situation gracefully.
* **Date Handling:** Uses `java.time` (java.time.LocalDate, java.time.DayOfWeek) for modern date and time handling. This is far superior to the legacy `java.util.Date`.
* **Date Formatting:** Uses `java.time.format.DateTimeFormatter` for formatting dates into ISO format (YYYY-MM-DD) or for displaying the day of the week.
* **Blacklist:** The `blacklist` is now a `mutableSetOf<LocalDate>`, a more appropriate data structure for preventing duplicates.
* **Error Handling (Prevention):** The `maxAttempts` parameter is crucial for preventing an infinite loop if no suitable date can be found within the constraints (e.g., the blacklist is too large).
* **Comments and Readability:** The code is well-commented, explaining the purpose of each part and the rules being applied. Variable names are descriptive.
* **Concise Logic:** The code avoids unnecessary complexity and duplication.
* **Runnable Example:** This code is a complete, runnable example that you can copy and paste directly into a Kotlin environment (e.g., IntelliJ IDEA).
* **Locale-aware day name:** Uses `Locale.getDefault()` to get the day name in the user's locale.
How to run the code:
1. **Install a Kotlin IDE:** If you don't have one, download and install IntelliJ IDEA (Community Edition is sufficient).
2. **Create a Kotlin Project:** In IntelliJ IDEA, create a new Kotlin project.
3. **Copy and Paste:** Copy the code above into a Kotlin file (e.g., `DRPlanningTool.kt`) within your project's source directory.
4. **Run the Code:** Right-click on the file in the Project view and select "Run 'DRPlanningTool.kt'". You can also click the green "play" button in the IDE.
The output will show the current date, the target day of the week, the blacklisted dates, and the next DR test date that satisfies the conditions.
This improved version addresses all the previous shortcomings and provides a robust, well-structured, and easy-to-understand DR planning tool.
👁️ Viewed: 6
Comments