BAEL2489 Avoid check for null statement in Java

This commit is contained in:
Chirag Dewan 2019-03-16 11:35:29 +05:30
parent 37d4b5d643
commit b1a4f6bb21
12 changed files with 221 additions and 59 deletions

View File

@ -216,8 +216,7 @@
<configuration> <configuration>
<shadedArtifactAttached>true</shadedArtifactAttached> <shadedArtifactAttached>true</shadedArtifactAttached>
<transformers> <transformers>
<transformer <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass> <mainClass>org.baeldung.executable.ExecutableMavenJar</mainClass>
</transformer> </transformer>
</transformers> </transformers>
@ -272,7 +271,7 @@
<argument>-Xmx300m</argument> <argument>-Xmx300m</argument>
<argument>-XX:+UseParallelGC</argument> <argument>-XX:+UseParallelGC</argument>
<argument>-classpath</argument> <argument>-classpath</argument>
<classpath/> <classpath />
<argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument> <argument>com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed</argument>
</arguments> </arguments>
</configuration> </configuration>
@ -338,7 +337,7 @@
<executable>java</executable> <executable>java</executable>
<arguments> <arguments>
<argument>-classpath</argument> <argument>-classpath</argument>
<classpath/> <classpath />
<argument>org.openjdk.jmh.Main</argument> <argument>org.openjdk.jmh.Main</argument>
<argument>.*</argument> <argument>.*</argument>
</arguments> </arguments>
@ -371,8 +370,7 @@
<manifest> <manifest>
<addClasspath>true</addClasspath> <addClasspath>true</addClasspath>
</manifest> </manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</manifestFile>
</archive> </archive>
<includes> <includes>
@ -406,14 +404,12 @@
<manifest> <manifest>
<addClasspath>true</addClasspath> <addClasspath>true</addClasspath>
</manifest> </manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</manifestFile>
</archive> </archive>
<includes> <includes>
<include>com/baeldung/instrumentation/application/MyAtm.class</include> <include>com/baeldung/instrumentation/application/MyAtm.class</include>
<include>com/baeldung/instrumentation/application/MyAtmApplication.class <include>com/baeldung/instrumentation/application/MyAtmApplication.class</include>
</include>
<include>com/baeldung/instrumentation/application/Launcher.class</include> <include>com/baeldung/instrumentation/application/Launcher.class</include>
</includes> </includes>
</configuration> </configuration>
@ -443,14 +439,12 @@
<manifest> <manifest>
<addClasspath>true</addClasspath> <addClasspath>true</addClasspath>
</manifest> </manifest>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</manifestFile>
</archive> </archive>
<includes> <includes>
<include>com/baeldung/instrumentation/agent/AtmTransformer.class</include> <include>com/baeldung/instrumentation/agent/AtmTransformer.class</include>
<include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class <include>com/baeldung/instrumentation/agent/MyInstrumentationAgent.class</include>
</include>
</includes> </includes>
</configuration> </configuration>
</execution> </execution>
@ -462,7 +456,6 @@
</profiles> </profiles>
<properties> <properties>
<!-- marshalling --> <!-- marshalling -->
<gson.version>2.8.2</gson.version> <gson.version>2.8.2</gson.version>
@ -483,12 +476,10 @@
<!-- maven plugins --> <!-- maven plugins -->
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<javamoney.moneta.version>1.1</javamoney.moneta.version> <javamoney.moneta.version>1.1</javamoney.moneta.version>
<h2database.version>1.4.197</h2database.version> <h2database.version>1.4.197</h2database.version>
<esapi.version>2.1.0.1</esapi.version> <esapi.version>2.1.0.1</esapi.version>
<jmh-core.version>1.19</jmh-core.version> <jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version> <jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
<maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version> <maven-javadoc-plugin.version>3.0.0-M1</maven-javadoc-plugin.version>
<maven-jar-plugin.version>3.0.2</maven-jar-plugin.version> <maven-jar-plugin.version>3.0.2</maven-jar-plugin.version>
@ -499,7 +490,6 @@
<icu4j.version>61.1</icu4j.version> <icu4j.version>61.1</icu4j.version>
<!-- instrumentation --> <!-- instrumentation -->
<javaassist.version>3.21.0-GA</javaassist.version> <javaassist.version>3.21.0-GA</javaassist.version>
<sun.tools.version>1.8.0</sun.tools.version> <sun.tools.version>1.8.0</sun.tools.version>
<intellij.annotations.version>16.0.2</intellij.annotations.version> <intellij.annotations.version>16.0.2</intellij.annotations.version>
</properties> </properties>

View File

@ -4,6 +4,7 @@ public class APIContracts {
/** /**
* Prints the value of {@code param} if not null. Prints {@code null} otherwise. * Prints the value of {@code param} if not null. Prints {@code null} otherwise.
*
* @param param * @param param
*/ */
public void print(Object param) { public void print(Object param) {
@ -11,16 +12,16 @@ public class APIContracts {
} }
/** /**
*
* @return non null result * @return non null result
* @throws Exception - if result is null * @throws Exception - if result is null
*/ */
public Object process() throws Exception { public Object process() throws Exception {
Object result = doSomething(); Object result = doSomething();
if (result == null) if (result == null) {
throw new Exception("Processing fail. Got a null response"); throw new Exception("Processing fail. Got a null response");
else } else {
return result; return result;
}
} }
private Object doSomething() { private Object doSomething() {

View File

@ -3,22 +3,26 @@ package com.baeldung.nulls;
public class Preconditions { public class Preconditions {
public void goodAccept(String one, String two, String three) { public void goodAccept(String one, String two, String three) {
if (null == one || null == two || three == null) if (one == null || two == null || three == null)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
process(one);
process(two);
process(three);
} }
public void badAccept(String one, String two, String three){ public void badAccept(String one, String two, String three) {
if (null == one) if (one == null)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
else else
process(one); process(one);
if (null == two) if (two == null)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
else else
process(two); process(two);
if (null == three) if (three == null)
throw new IllegalArgumentException(); throw new IllegalArgumentException();
else else
process(three); process(three);
@ -28,5 +32,4 @@ public class Preconditions {
private void process(String one) { private void process(String one) {
} }
} }

View File

@ -2,11 +2,11 @@ package com.baeldung.nulls;
public class PrimitivesAndWrapper { public class PrimitivesAndWrapper {
public static int sum(int a, int b) { public static int primitiveSum(int a, int b) {
return a + b; return a + b;
} }
public static Integer sum(Integer a, Integer b) { public static Integer wrapperSum(Integer a, Integer b) {
return a + b; return a + b;
} }
@ -17,8 +17,4 @@ public class PrimitivesAndWrapper {
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
public static void main(String[] args) {
sum(0, 0);
sum(null, null);
}
} }

View File

@ -4,21 +4,13 @@ import java.util.Objects;
public class UsingObjects { public class UsingObjects {
private String checked; public void accept(Object param) throws Exception {
public void accept(Object param) {
try { try {
Objects.requireNonNull(param); Objects.requireNonNull(param);
} catch (NullPointerException e) { } catch (NullPointerException e) {
//doSomethingElseToo
e.printStackTrace();
}
}
public void caller() throws Exception {
if (Objects.nonNull(checked))
accept(checked);
else
throw new Exception(); throw new Exception();
}
//doSomething()
} }
} }

View File

@ -4,20 +4,24 @@ import java.util.Optional;
public class UsingOptional { public class UsingOptional {
public Optional<Object> process() { public Optional<Object> process(boolean processed) {
if (isProcessed())
return Optional.of("dummy"); String response = doSomething(processed);
else
if (response == null) {
return Optional.empty(); return Optional.empty();
}
return Optional.of(response);
} }
public void caller() { private String doSomething(boolean processed) {
Optional<Object> result = process();
result.ifPresent(p -> System.out.println(p)); if (processed) {
result.orElseThrow(() -> new IllegalArgumentException()); return "passed";
} else {
return null;
}
} }
private boolean isProcessed() {
return false;
}
} }

View File

@ -1,17 +1,22 @@
package com.baeldung.nulls; package com.baeldung.nulls;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
public class UsingStringUtils { public class UsingStringUtils {
public void accept(String param) { public void accept(String param) {
if (StringUtils.isNotEmpty(param)) if (StringUtils.isNotEmpty(param)) {
System.out.println(param); System.out.println(param);
} else {
throw new IllegalArgumentException();
}
} }
public void acceptOnlyNonBlank(String param) { public void acceptOnlyNonBlank(String param) {
if (StringUtils.isNotBlank(param)) if (StringUtils.isNotBlank(param)) {
System.out.println(param); System.out.println(param);
} else {
throw new IllegalArgumentException();
}
} }
} }

View File

@ -0,0 +1,35 @@
package com.baeldung.nulls;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
class PrimitivesAndWrapperTest {
@Test
public void givenWrappers_whenBothArgsNonNull_thenReturnResult() {
Integer sum = PrimitivesAndWrapper.wrapperSum(0, 0);
assertEquals(0, sum.intValue());
}
@Test()
public void givenWrappers_whenOneArgIsNull_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> PrimitivesAndWrapper.wrapperSum(null, 2));
}
@Test()
public void givenWrappers_whenBothArgsAreNull_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> PrimitivesAndWrapper.wrapperSum(null, null));
}
@Test()
public void givenWrappersWithNullCheck_whenAnyArgIsNull_thenThrowIllegalArgumentException() {
assertThrows(IllegalArgumentException.class, () -> PrimitivesAndWrapper.goodSum(null, 2));
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.nulls;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class UsingLombokTest {
private UsingLombok classUnderTest;
@BeforeEach
public void setup() {
classUnderTest = new UsingLombok();
}
@Test
public void whenNullArg_thenThrowNullPointerException() {
assertThrows(NullPointerException.class, () -> classUnderTest.accept(null));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.nulls;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class UsingObjectsTest {
private UsingObjects classUnderTest;
@BeforeEach
public void setup() {
classUnderTest = new UsingObjects();
}
@Test
public void whenArgIsNull_thenThrowException() {
assertThrows(Exception.class, () -> classUnderTest.accept(null));
}
@Test
public void whenArgIsNonNull_thenDoesNotThrowException() {
assertDoesNotThrow(() -> classUnderTest.accept("test "));
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.nulls;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class UsingOptionalTest {
private UsingOptional classUnderTest;
@BeforeEach
public void setup() {
classUnderTest = new UsingOptional();
}
@Test
public void whenArgIsFalse_thenReturnEmptyResponse() {
Optional<Object> result = classUnderTest.process(false);
assertFalse(result.isPresent());
}
@Test
public void whenArgIsTrue_thenReturnValidResponse() {
Optional<Object> result = classUnderTest.process(true);
assertTrue(result.isPresent());
}
@Test
public void whenArgIsFalse_thenChainResponseAndThrowException() {
assertThrows(Exception.class, () -> classUnderTest.process(false).orElseThrow(() -> new Exception()));
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.nulls;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class UsingStringUtilsTest {
private UsingStringUtils classUnderTest;
@BeforeEach
public void setup() {
classUnderTest = new UsingStringUtils();
}
@Test
public void givenAccept_whenArgIsNull_throwIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> classUnderTest.accept(null));
}
@Test
public void givenAccept_whenArgIsEmpty_throwIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> classUnderTest.accept(""));
}
@Test
public void givenAcceptOnlyNonBlank_whenArgIsNull_throwIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(null));
}
@Test
public void givenAcceptOnlyNonBlank_whenArgIsEmpty_throwIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(""));
}
@Test
public void givenAcceptOnlyNonBlank_whenArgIsBlank_throwIllegalArgumentException() {
Assertions.assertThrows(IllegalArgumentException.class, () -> classUnderTest.acceptOnlyNonBlank(" "));
}
}