|
| 1 | +package pl.mperor.lab.java.lang.element; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Assertions; |
| 4 | +import org.junit.jupiter.api.Test; |
| 5 | + |
| 6 | +import java.util.Optional; |
| 7 | + |
| 8 | +public class OptionalTest { |
| 9 | + |
| 10 | + @Test |
| 11 | + public void testOptionalImperatively() { |
| 12 | + Assertions.assertFalse(SomeAPI.getNameById(0).isPresent()); |
| 13 | + // Please for(get), do not use get, instead use orElseThrow() / orElse("default") |
| 14 | + Assertions.assertEquals("default", SomeAPI.getNameById(0).orElse("default")); |
| 15 | + Assertions.assertEquals("some name", SomeAPI.getNameById(1).orElseThrow()); |
| 16 | + } |
| 17 | + |
| 18 | + @Test |
| 19 | + public void testOptionalFunctionally() { |
| 20 | + SomeAPI.getNameById(1).ifPresentOrElse( |
| 21 | + name -> Assertions.assertEquals("some name", name), |
| 22 | + () -> Assertions.fail() |
| 23 | + ); |
| 24 | + } |
| 25 | + |
| 26 | + static class SomeAPI { |
| 27 | + |
| 28 | + // 1. Return a reference if the value will always exist |
| 29 | + // 2. Return an Optional<T> if the value may or may not exist |
| 30 | + public static Optional<String> getNameById(long id) { |
| 31 | + if (id == 0) { |
| 32 | + return Optional.empty(); |
| 33 | + } |
| 34 | + |
| 35 | + return Optional.of("some name"); |
| 36 | + } |
| 37 | + |
| 38 | + // 3. Do not use Optional<T> for fields - overhead with little benefit |
| 39 | + private String config; |
| 40 | + |
| 41 | + // 4. Do not user Optional<T> for method parameters - user overloading instead |
| 42 | + public void setConfig(String config) { |
| 43 | + this.config = config; |
| 44 | + } |
| 45 | + |
| 46 | + public void setConfig() { |
| 47 | + setConfig("default"); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments