Add initialize(..) operator to promote initialization safety.

The initialize operator replaces the common initialization safety pattern using an if-then-else or Java's ternary operator to ensure that a collaborator reference has bee properly initialized:

target = target != null ? target : new Target();
This commit is contained in:
John Blum
2020-07-08 13:26:57 -07:00
parent 2da58cc548
commit 251f762c2d
2 changed files with 61 additions and 2 deletions

View File

@@ -95,7 +95,7 @@ public class ObjectUtilsUnitTests {
}
@Test(expected = IllegalArgumentException.class)
public void asPdxInstanceTypeReturnNonMatchingType() {
public void asPdxInstanceTypeReturningNonMatchingType() {
C source = new C();
@@ -300,6 +300,16 @@ public class ObjectUtilsUnitTests {
}
}
@Test
public void initializeWithNonNullTarget() {
assertThat(ObjectUtils.initialize("test", () -> "mock")).isEqualTo("test");
}
@Test
public void initializeWithNullTarget() {
assertThat(ObjectUtils.initialize(null, () -> "mock")).isEqualTo("mock");
}
@Test
public void invokeMethodOnObjectReturnsValue() {
assertThat(ObjectUtils.<String>invoke(new TestObject(), "testMethod")).isEqualTo("TEST");