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 <vlad.galuska@hibyte.ro>
This commit is contained in:
Vlad 2023-09-28 19:05:39 +03:00 committed by GitHub
parent eabaf2764d
commit 204555a479
8 changed files with 366 additions and 7 deletions

View File

@ -12,6 +12,12 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<properties>
<maven.compiler.source.version>21</maven.compiler.source.version>
<maven.compiler.target.version>21</maven.compiler.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
@ -20,14 +26,22 @@
<configuration>
<source>21</source>
<target>21</target>
<compilerArgs>--enable-preview</compilerArgs>
<!-- Needed due to a bug with JDK 21, described here: https://issues.apache.org/jira/browse/MCOMPILER-546?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel&focusedCommentId=17767513 -->
<debug>false</debug>
<compilerArgs>
<arg>--enable-preview</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>--enable-preview</argLine>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source.version>21</maven.compiler.source.version>
<maven.compiler.target.version>21</maven.compiler.target.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.unnamed.variables;
public record Car<T extends Engine>(String name, String color, T engine) { }
abstract class Engine { }
class GasEngine extends Engine { }
class ElectricEngine extends Engine { }
class HybridEngine extends Engine { }

View File

@ -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";
};
}
}

View File

@ -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<Car<?>> 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<Car<?>> 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<Car<?>> cars) {
sendOneTimeNotification();
for (int i = 0; i < cars.size(); i++) {
// Notify car
}
}
static void sendNotificationToCarsWithUnnamedVariable(Collection<Car<?>> 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<Car<?>> cars) {
var x = cars.poll();
var y = cars.poll();
var z = cars.poll();
return x;
}
static Car<?> removeThreeCarsAndReturnFirstRemovedWithUnnamedVariables(Queue<Car<?>> 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<String, List<Car<?>>> getCarsByFirstLetterWithNamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> carMap = new HashMap<>();
cars.forEach(car ->
carMap.computeIfAbsent(car.name().substring(0, 1), firstLetter -> new ArrayList<>()).add(car)
);
return carMap;
}
static Map<String, List<Car<?>>> getCarsByFirstLetterWithUnnamedVariables(List<Car<?>> cars) {
Map<String, List<Car<?>>> 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());
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.unnamed.variables;
import java.util.List;
class CarScenario {
protected final List<Car<?>> cars = List.of(
new Car<>("Mitsubishi", "blue", new GasEngine()),
new Car<>("Toyota", "red", new ElectricEngine()),
new Car<>("Jaguar", "white", new HybridEngine())
);
}

View File

@ -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)));
}
}

View File

@ -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());
}
}