如何简洁消除Java图书查询代码中的条件判断?
Great question! Let’s clean up that conditional logic without breaking your existing widely-used findBookByTitle and findBookByIsbn methods. The key is to use method references and a lookup map to dynamically select the right query strategy based on input parameters—no messy if-else checks required.
Step 1: Create a Query Strategy Map
First, define a static map that maps your parameter keys (-T, -I) to the corresponding query methods in LibraryService. This acts as a reusable "decision table" instead of hardcoding conditionals:
// Define as a static constant to avoid reinitializing on every call private static final Map<String, Function<LibraryService, Function<String, Book>>> QUERY_STRATEGIES; static { QUERY_STRATEGIES = new HashMap<>(); // Map "-T" parameter to the findBookByTitle method QUERY_STRATEGIES.put("-T", libraryService -> libraryService::findBookByTitle); // Map "-I" parameter to the findBookByIsbn method QUERY_STRATEGIES.put("-I", libraryService -> libraryService::findBookByIsbn); }
Step 2: Replace If-Else with Dynamic Lookup
Now, instead of checking each parameter manually, just find the existing parameter key and execute the matched query method directly:
Map<String, String> args = new HashMap<>(); args.put("-T", "Tom Sawyer"); // args.put("-I", "1112223334"); // Fetch the valid parameter key (you mentioned you’ve handled the "none exist" case) String paramKey = args.keySet().stream().findFirst().orElseThrow(() -> new RuntimeException("No valid query parameter")); // Run the corresponding query Book book = QUERY_STRATEGIES.get(paramKey) .apply(libraryService) .apply(args.get(paramKey));
Why This Approach Works
- No more if-else clutter: The map handles all decision logic cleanly and readably.
- Preserves existing methods: Your
findBookByTitleandfindBookByIsbnstay untouched, so they can still be used anywhere else in your codebase. - Easy to extend: If you add a new query parameter later (like
-Afor author), just add a new entry to theQUERY_STRATEGIESmap—no need to rewrite conditional code. - Modern Java style: Uses function interfaces and method references for concise, maintainable code.
Bonus: Streamlined One-Liner (Optional)
For even tighter code, combine the key lookup and method execution into a single stream pipeline:
Book book = args.entrySet().stream() .findFirst() .map(entry -> QUERY_STRATEGIES.get(entry.getKey()) .apply(libraryService) .apply(entry.getValue())) .orElseThrow(() -> new RuntimeException("No valid query parameter"));
内容的提问来源于stack exchange,提问作者steve1337

