Refactor `Menu` class: Simplify `updateDisplay` method, remove redundant logic, and...
authorSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Sun, 25 Jan 2026 12:10:24 +0000 (14:10 +0200)
committerSvjatoslav Agejenko <svjatoslav@svjatoslav.eu>
Sun, 25 Jan 2026 12:10:24 +0000 (14:10 +0200)
src/main/java/eu/svjatoslav/commons/cli_helper/Menu.java

index 8aedcad..73356fb 100644 (file)
@@ -36,7 +36,13 @@ public class Menu {
             int lastTotalLines = 0;
 
             while (true) {
-                selectedIndex = updateDisplay(prompt, options, selectedIndex, filterString, lastTotalLines);
+
+                List<String> filtered = filterOptions(options, filterString);
+
+                // Clamp selected to valid range
+                selectedIndex = Math.max(0, Math.min(selectedIndex, filtered.size() - 1));
+
+                updateDisplay(prompt, filtered, selectedIndex, filterString, lastTotalLines);
                 lastTotalLines = getCurrentTotalLines(options, filterString);
 
                 int c = System.in.read();
@@ -61,7 +67,6 @@ public class Menu {
 
                 // Handle Enter key
                 else if (c == 13 || c == 10) {
-                    List<String> filtered = filterOptions(options, filterString.toString());
                     if (filtered.isEmpty()) {
                         return null;
                     }
@@ -172,16 +177,12 @@ public class Menu {
     /**
      * Updates the display based on the current state and returns the adjusted selected index.
      */
-    private static int updateDisplay(String prompt, List<String> options, int selected, String filter, int lastTotalLines) {
-        List<String> filtered = filterOptions(options, filter);
+    private static void updateDisplay(String prompt, List<String> filtered, int selected, String filter, int lastTotalLines) {
 
         if (filtered.isEmpty()) {
             filtered = Collections.singletonList("No matches found");
         }
 
-        // Clamp selected to valid range
-        selected = Math.max(0, Math.min(selected, filtered.size() - 1));
-
         // ────────────────────────────────────────────────
         // 1. Position cursor at the START of our display area
         // ────────────────────────────────────────────────
@@ -210,8 +211,6 @@ public class Menu {
         System.out.print("\r");
 
         System.out.flush();  // ensure immediate display
-
-        return selected;
     }
 
     private static int getCurrentTotalLines(List<String> options, String filter) {