Add utility method for null checks.

This commit is contained in:
akwizgran
2019-05-09 13:17:23 +01:00
parent dd50f4bcd4
commit afa0b96293
5 changed files with 24 additions and 7 deletions

View File

@@ -6,10 +6,20 @@ import javax.annotation.Nullable;
public class NullSafety {
/**
* Stand-in for `Objects.requireNonNull()`.
* Stand-in for {@code Objects.requireNonNull()}.
*/
public static <T> T requireNonNull(@Nullable T t) {
if (t == null) throw new NullPointerException();
return t;
}
/**
* Checks that exactly one of the arguments is null.
*
* @throws AssertionError If both or neither of the arguments are null
*/
public static void requireExactlyOneNull(@Nullable Object a,
@Nullable Object b) {
if ((a == null) == (b == null)) throw new AssertionError();
}
}

View File

@@ -9,6 +9,8 @@ import org.briarproject.bramble.api.plugin.TransportId;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireExactlyOneNull;
@Immutable
@NotNullByDefault
public class StreamContext {
@@ -26,8 +28,7 @@ public class StreamContext {
@Nullable PendingContactId pendingContactId,
TransportId transportId, SecretKey tagKey, SecretKey headerKey,
long streamNumber, boolean handshakeMode) {
if ((contactId == null) == (pendingContactId == null))
throw new IllegalArgumentException();
requireExactlyOneNull(contactId, pendingContactId);
this.contactId = contactId;
this.pendingContactId = pendingContactId;
this.transportId = transportId;

View File

@@ -7,6 +7,8 @@ import org.briarproject.bramble.api.nullsafety.NotNullByDefault;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static org.briarproject.bramble.api.nullsafety.NullSafety.requireExactlyOneNull;
/**
* A set of keys for communicating with a given contact or pending contact
* over a given transport.
@@ -24,8 +26,7 @@ public class TransportKeySet {
public TransportKeySet(KeySetId keySetId, @Nullable ContactId contactId,
@Nullable PendingContactId pendingContactId, TransportKeys keys) {
if ((contactId == null) == (pendingContactId == null))
throw new IllegalArgumentException();
requireExactlyOneNull(contactId, pendingContactId);
this.keySetId = keySetId;
this.contactId = contactId;
this.pendingContactId = pendingContactId;