From ad05e9e95a0143007dc6778e4c3f205e93e9eb9f Mon Sep 17 00:00:00 2001 From: David Guler Date: Tue, 8 Nov 2022 07:31:04 +0100 Subject: [PATCH] refactor: remove exception-based control-flow --- .../plantList/PlantListModel.java | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java b/src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java index 4bfc9b1..ffccb30 100644 --- a/src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java +++ b/src/main/java/ch/zhaw/gartenverwaltung/plantList/PlantListModel.java @@ -116,16 +116,17 @@ public class PlantListModel { if (searchString.length() == 0) { return getPlantList(zone); } else if (searchString.charAt(0) == '#') { - try { - return getFilteredPlantListById(zone, Long.parseLong(searchString.substring(1))); - } catch (NumberFormatException e) { + if (isPositiveIntegral(searchString.substring(1))) { + Long searchId = Long.parseLong(searchString.substring(1)); + return getFilteredPlantListById(zone, searchId); + } else { return new ArrayList<>(); } } else { String caseInsensitiveSearchString = searchString.toLowerCase(); return getFilteredPlantList(zone, plant -> - plant.name().toLowerCase().contains(caseInsensitiveSearchString) || - plant.description().toLowerCase().contains(caseInsensitiveSearchString) + plant.name().toLowerCase().contains(caseInsensitiveSearchString) || + plant.description().toLowerCase().contains(caseInsensitiveSearchString) ); } } @@ -169,15 +170,24 @@ public class PlantListModel { } /** - * * @param zone selected hardiness zone * @param from the earliest date to for the filter - * @param to the lastest date for the filter + * @param to the lastest date for the filter * @return List of Plants with selected saison * @throws HardinessZoneNotSetException If no {@link HardinessZone} was specified - * @throws IOException If the database cannot be accessed + * @throws IOException If the database cannot be accessed */ public List getFilteredPlantListBySaisonWithoutGrowthPhase(HardinessZone zone, MonthDay from, MonthDay to) throws HardinessZoneNotSetException, IOException { return getFilteredPlantList(zone, plant -> plant.lifecycle().stream().anyMatch(growthPhase -> growthPhase.startDate().compareTo(from) >= 0 && (growthPhase.startDate().compareTo(to) <= 0))); } + + /** + * Check if a string can safely be parsed as a positive Integral value (short/int/long) + * + * @param subject The string to be tested + * @return Whether the string contains only digits + */ + private boolean isPositiveIntegral(String subject) { + return subject != null && subject.matches("[0-9]+"); + } }