001package java7;
002
003import com.sandwich.koan.Koan;
004
005import java.util.Objects;
006
007import static com.sandwich.koan.constant.KoanConstants.__;
008import static com.sandwich.util.Assert.assertEquals;
009
010public class AboutRequireNotNull {
011
012    @Koan
013    public void failArgumentValidationWithRequireNotNull() {
014        // This koan demonstrates the use of Objects.requireNotNull
015        // in place of traditional argument validation using exceptions
016        String s = "";
017        try {
018            s += validateUsingRequireNotNull(null);
019        } catch (NullPointerException ex) {
020            s = "caught a NullPointerException";
021        }
022        assertEquals(s, __);
023    }
024
025    @Koan
026    public void passArgumentValidationWithRequireNotNull() {
027        // This koan demonstrates the use of Objects.requireNotNull
028        // in place of traditional argument validation using exceptions
029        String s = "";
030        try {
031            s += validateUsingRequireNotNull("valid");
032        } catch (NullPointerException ex) {
033            s = "caught a NullPointerException";
034        }
035        assertEquals(s, __);
036    }
037
038    private int validateUsingRequireNotNull(String str) {
039        // If you're only concerned with null values requireNotNull
040        // is concise and the point of the NullPointerException it
041        // throws is clear, though you can optionally provide a
042        // description as well
043        return Objects.requireNonNull(str).length();
044    }
045
046}