From 204555a479341a07a14f3fc220a9c7ca6d60881e Mon Sep 17 00:00:00 2001 From: Vlad <48989383+VladGaluska@users.noreply.github.com> Date: Thu, 28 Sep 2023 19:05:39 +0300 Subject: [PATCH] Bael 6961 Unnamed Patterns and Variables (#14829) * BAEL-6961 Added first code snippets * Added code for article * Added debug configuration * Build trigger --------- Co-authored-by: Vlad --- core-java-modules/core-java-21/README.md | 2 +- core-java-modules/core-java-21/pom.xml | 26 +++- .../com/baeldung/unnamed/variables/Car.java | 11 ++ .../unnamed/variables/UnnamedPatterns.java | 50 +++++++ .../unnamed/variables/UnnamedVariables.java | 134 ++++++++++++++++++ .../unnamed/variables/CarScenario.java | 13 ++ .../variables/UnnamedPatternsUnitTest.java | 44 ++++++ .../variables/UnnamedVariablesUnitTest.java | 93 ++++++++++++ 8 files changed, 366 insertions(+), 7 deletions(-) create mode 100644 core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/Car.java create mode 100644 core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedPatterns.java create mode 100644 core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedVariables.java create mode 100644 core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/CarScenario.java create mode 100644 core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedPatternsUnitTest.java create mode 100644 core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedVariablesUnitTest.java diff --git a/core-java-modules/core-java-21/README.md b/core-java-modules/core-java-21/README.md index 2e7130c906..04f99a244b 100644 --- a/core-java-modules/core-java-21/README.md +++ b/core-java-modules/core-java-21/README.md @@ -1,2 +1,2 @@ ## Relevant Articles -- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections) +- [Sequenced Collections in Java 21](https://www.baeldung.com/java-21-sequenced-collections) \ No newline at end of file diff --git a/core-java-modules/core-java-21/pom.xml b/core-java-modules/core-java-21/pom.xml index 0504f787c6..7b8fa9063f 100644 --- a/core-java-modules/core-java-21/pom.xml +++ b/core-java-modules/core-java-21/pom.xml @@ -12,6 +12,12 @@ 0.0.1-SNAPSHOT + + 21 + 21 + UTF-8 + + @@ -20,14 +26,22 @@ 21 21 - --enable-preview + + false + + --enable-preview + + + org.apache.maven.plugins + maven-surefire-plugin + + --enable-preview + + + - - 21 - 21 - UTF-8 - + \ No newline at end of file diff --git a/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/Car.java b/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/Car.java new file mode 100644 index 0000000000..8f51c03539 --- /dev/null +++ b/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/Car.java @@ -0,0 +1,11 @@ +package com.baeldung.unnamed.variables; + +public record Car(String name, String color, T engine) { } + +abstract class Engine { } + +class GasEngine extends Engine { } + +class ElectricEngine extends Engine { } + +class HybridEngine extends Engine { } \ No newline at end of file diff --git a/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedPatterns.java b/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedPatterns.java new file mode 100644 index 0000000000..310ce621f9 --- /dev/null +++ b/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedPatterns.java @@ -0,0 +1,50 @@ +package com.baeldung.unnamed.variables; + +public class UnnamedPatterns { + + static String getObjectsColorWithNamedPattern(Object object) { + if (object instanceof Car(String name, String color, Engine engine)) { + return color; + } + return "No color!"; + } + + static String getObjectsColorWithUnnamedPattern(Object object) { + if (object instanceof Car(_, String color, _)) { + return color; + } + return "No color!"; + } + + static String getObjectsColorWithSwitchAndNamedPattern(Object object) { + return switch (object) { + case Car(String name, String color, Engine engine) -> color; + default -> "No color!"; + }; + } + + static String getObjectsColorWithSwitchAndUnnamedPattern(Object object) { + return switch (object) { + case Car(_, String color, _) -> color; + default -> "No color!"; + }; + } + + static String getEngineTypeWithNamedPattern(Car car) { + return switch (car) { + case Car(String name, String color, GasEngine engine) -> "gas"; + case Car(String name, String color, ElectricEngine engine) -> "electric"; + case Car(String name, String color, HybridEngine engine) -> "hybrid"; + default -> "none"; + }; + } + + static String getEngineTypeWithUnnamedPattern(Car car) { + return switch (car) { + case Car(_, _, GasEngine _) -> "gas"; + case Car(_, _, ElectricEngine _) -> "electric"; + case Car(_, _, HybridEngine _) -> "hybrid"; + default -> "none"; + }; + } +} diff --git a/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedVariables.java b/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedVariables.java new file mode 100644 index 0000000000..82e76b40a4 --- /dev/null +++ b/core-java-modules/core-java-21/src/main/java/com/baeldung/unnamed/variables/UnnamedVariables.java @@ -0,0 +1,134 @@ +package com.baeldung.unnamed.variables; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Queue; + +class Transaction implements AutoCloseable { + + @Override + public void close() { + System.out.println("Closed!"); + } +} + +public class UnnamedVariables { + + static int countCarsOverLimitWithNamedVariable(Collection> cars, int limit) { + var total = 0; + var totalOverLimit = 0; + for (var car : cars) { + total++; + if (total > limit) { + totalOverLimit++; + // side effect + } + } + return totalOverLimit; + } + + static int countCarsOverLimitWithUnnamedVariable(Collection> cars, int limit) { + var total = 0; + var totalOverLimit = 0; + for (var _ : cars) { + total++; + if (total > limit) { + totalOverLimit++; + // side effect + } + } + return totalOverLimit; + } + + static void sendNotificationToCarsWithNamedVariable(Collection> cars) { + sendOneTimeNotification(); + for (int i = 0; i < cars.size(); i++) { + // Notify car + } + } + + static void sendNotificationToCarsWithUnnamedVariable(Collection> cars) { + for (int i = 0, _ = sendOneTimeNotification(); i < cars.size(); i++) { + // Notify car + } + } + + private static int sendOneTimeNotification() { + System.out.println("Sending one time notification!"); + return 1; + } + + static Car removeThreeCarsAndReturnFirstRemovedWithNamedVariables(Queue> cars) { + var x = cars.poll(); + var y = cars.poll(); + var z = cars.poll(); + return x; + } + + static Car removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue> cars) { + var car = cars.poll(); + var _ = cars.poll(); + var _ = cars.poll(); + return car; + } + + static void handleCarExceptionWithNamedVariables(Car car) { + try { + someOperationThatFails(car); + } catch (IllegalStateException ex) { + System.out.println("Got an illegal state exception for: " + car.name()); + } catch (RuntimeException ex) { + System.out.println("Got a runtime exception!"); + } + } + + static void handleCarExceptionWithUnnamedVariables(Car car) { + try { + someOperationThatFails(car); + } catch (IllegalStateException | NumberFormatException _) { + System.out.println("Got an illegal state exception for: " + car.name()); + } catch (RuntimeException _) { + System.out.println("Got a runtime exception!"); + } + } + + static void obtainTransactionAndUpdateCarWithNamedVariables(Car car) { + try (var transaction = new Transaction()) { + updateCar(car); + } + } + + static void obtainTransactionAndUpdateCarWithUnnamedVariables(Car car) { + try (var _ = new Transaction()) { + updateCar(car); + } + } + + static void updateCar(Car car) { + // Some update logic + System.out.println("Car updated!"); + } + + static Map>> getCarsByFirstLetterWithNamedVariables(List> cars) { + Map>> carMap = new HashMap<>(); + cars.forEach(car -> + carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car) + ); + return carMap; + } + + static Map>> getCarsByFirstLetterWithUnnamedVariables(List> cars) { + Map>> carMap = new HashMap<>(); + cars.forEach(car -> + carMap.computeIfAbsent(car.name().substring(0, 1), _ -> new ArrayList<>()).add(car) + ); + return carMap; + } + + private static void someOperationThatFails(Car car) { + throw new IllegalStateException("Triggered exception for: " + car.name()); + } +} diff --git a/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/CarScenario.java b/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/CarScenario.java new file mode 100644 index 0000000000..2acb83cdef --- /dev/null +++ b/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/CarScenario.java @@ -0,0 +1,13 @@ +package com.baeldung.unnamed.variables; + +import java.util.List; + +class CarScenario { + + protected final List> cars = List.of( + new Car<>("Mitsubishi", "blue", new GasEngine()), + new Car<>("Toyota", "red", new ElectricEngine()), + new Car<>("Jaguar", "white", new HybridEngine()) + ); + +} diff --git a/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedPatternsUnitTest.java b/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedPatternsUnitTest.java new file mode 100644 index 0000000000..9d860a201a --- /dev/null +++ b/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedPatternsUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.unnamed.variables; + +import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithNamedPattern; +import static com.baeldung.unnamed.variables.UnnamedPatterns.getEngineTypeWithUnnamedPattern; +import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithNamedPattern; +import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndNamedPattern; +import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithSwitchAndUnnamedPattern; +import static com.baeldung.unnamed.variables.UnnamedPatterns.getObjectsColorWithUnnamedPattern; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class UnnamedPatternsUnitTest extends CarScenario { + + @Test + public void whenExtractingColorWithNamedPatterns_thenReturnBlue() { + assertEquals("blue", getObjectsColorWithNamedPattern(cars.get(0))); + } + + @Test + public void whenExtractingColorWithUnnamedPatterns_thenReturnBlue() { + assertEquals("blue", getObjectsColorWithUnnamedPattern(cars.get(0))); + } + + @Test + public void whenExtractingColorWithSwitchAndNamedPatterns_thenReturnBlue() { + assertEquals("blue", getObjectsColorWithSwitchAndNamedPattern(cars.get(0))); + } + + @Test + public void whenExtractingColorWithSwitchAndUnnamedPatterns_thenReturnBlue() { + assertEquals("blue", getObjectsColorWithSwitchAndUnnamedPattern(cars.get(0))); + } + + @Test + public void whenExtractingEngineTypeWithNamedPatterns_thenReturnGas() { + assertEquals("gas", getEngineTypeWithNamedPattern(cars.get(0))); + } + + @Test + public void whenExtractingEngineTypeWithUnnamedPatterns_thenReturnGas() { + assertEquals("gas", getEngineTypeWithUnnamedPattern(cars.get(0))); + } +} diff --git a/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedVariablesUnitTest.java b/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedVariablesUnitTest.java new file mode 100644 index 0000000000..094879c277 --- /dev/null +++ b/core-java-modules/core-java-21/src/test/java/com/baeldung/unnamed/variables/UnnamedVariablesUnitTest.java @@ -0,0 +1,93 @@ +package com.baeldung.unnamed.variables; + +import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithNamedVariable; +import static com.baeldung.unnamed.variables.UnnamedVariables.countCarsOverLimitWithUnnamedVariable; +import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithNamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.getCarsByFirstLetterWithUnnamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithNamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.handleCarExceptionWithUnnamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithNamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.obtainTransactionAndUpdateCarWithUnnamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithNamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables; +import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithNamedVariable; +import static com.baeldung.unnamed.variables.UnnamedVariables.sendNotificationToCarsWithUnnamedVariable; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.LinkedList; + +import org.junit.jupiter.api.Test; + +public class UnnamedVariablesUnitTest extends CarScenario { + + @Test + public void whenCountingCarsOverLimitWithNamedVariables_thenShouldReturnOne() { + assertEquals(1, countCarsOverLimitWithNamedVariable(cars, 2)); + } + + @Test + public void whenCountingCarsOverLimitWithUnnamedVariables_thenShouldReturnOne() { + assertEquals(1, countCarsOverLimitWithUnnamedVariable(cars, 2)); + } + + @Test + public void whenNotifyingCarsWithNamedVariables_thenShouldNotFail() { + assertDoesNotThrow(() -> sendNotificationToCarsWithNamedVariable(cars)); + } + + @Test + public void whenNotifyingCarsWithUnnamedVariables_thenShouldNotFail() { + assertDoesNotThrow(() -> sendNotificationToCarsWithUnnamedVariable(cars)); + } + + @Test + public void whenPollingCarsWithNamedVariables_thenReturnFirstOneAndEmptyQueue() { + var carQueue = new LinkedList<>(cars); + assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithNamedVariables(carQueue).name()); + assertEquals(0, carQueue.size()); + } + + @Test + public void whenPollingCarsWithUnnamedVariables_thenReturnFirstOneAndEmptyQueue() { + var carQueue = new LinkedList<>(cars); + assertEquals("Mitsubishi", removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(carQueue).name()); + assertEquals(0, carQueue.size()); + } + + @Test + public void whenHandlingExceptionWithNamedVariables_thenNoExceptionIsThrown() { + assertDoesNotThrow(() -> handleCarExceptionWithNamedVariables(cars.get(0))); + } + + @Test + public void whenHandlingExceptionWithUnnamedVariables_thenNoExceptionIsThrown() { + assertDoesNotThrow(() -> handleCarExceptionWithUnnamedVariables(cars.get(0))); + } + + @Test + public void whenHandlingTransactionUpdateWithNamedVariables_thenNoExceptionIsThrown() { + assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithNamedVariables(cars.get(0))); + } + + @Test + public void whenHandlingTransactionUpdateWithUnnamedVariables_thenNoExceptionIsThrown() { + assertDoesNotThrow(() -> obtainTransactionAndUpdateCarWithUnnamedVariables(cars.get(0))); + } + + @Test + public void whenGettingCarsByFirstLetterWithNamedVariables_thenHaveThreeKeys() { + var carsByLetter = getCarsByFirstLetterWithNamedVariables(cars); + assertEquals(1, carsByLetter.get("M").size()); + assertEquals(1, carsByLetter.get("T").size()); + assertEquals(1, carsByLetter.get("J").size()); + } + + @Test + public void whenGettingCarsByFirstLetterWithUnnamedVariables_thenHaveThreeKeys() { + var carsByLetter = getCarsByFirstLetterWithUnnamedVariables(cars); + assertEquals(1, carsByLetter.get("M").size()); + assertEquals(1, carsByLetter.get("T").size()); + assertEquals(1, carsByLetter.get("J").size()); + } +}