Introduce a checkNotNull helper
When using @NonNull annotations in new code, if I write public void setFrobber(@NonNull frobber) { this.frobber = frobber; } then consumers of the JGit library that do not have nullness checking enabled can easily pass in null by mistake. On the other hand, if I write public void setFrobber(@NonNull frobber) { if (frobber == null) { throw new NullPointerException(); } this.frobber = frobber; } then Eclipse JDT complains: Null comparison always yields false: The variable frobber is specified as @NonNull Add a checkNotNull helper that offers the best of both worlds: public void setFrobber(@NonNull frobber) { this.frobber = checkNotNull(frobber); } Briefer code, null check is intact, and no warning. Inspired by Guava's com.google.common.base.Preconditions.checkNotNull. Change-Id: If59588d13a1119e899657ed2296931ea18ed0e2a
This commit is contained in:
parent
5bcee1ef69
commit
3551e443fc
|
@ -43,6 +43,8 @@
|
|||
*/
|
||||
package org.eclipse.jgit.api;
|
||||
|
||||
import static org.eclipse.jgit.lib.Constants.checkNotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
|
@ -220,9 +222,7 @@ public Git(Repository repo) {
|
|||
}
|
||||
|
||||
Git(Repository repo, boolean closeRepo) {
|
||||
if (repo == null)
|
||||
throw new NullPointerException();
|
||||
this.repo = repo;
|
||||
this.repo = checkNotNull(repo);
|
||||
this.closeRepo = closeRepo;
|
||||
}
|
||||
|
||||
|
|
|
@ -58,7 +58,7 @@
|
|||
import org.eclipse.jgit.util.MutableInteger;
|
||||
|
||||
/**
|
||||
* Misc. constants used throughout JGit.
|
||||
* Misc. constants and helpers used throughout JGit.
|
||||
*/
|
||||
@SuppressWarnings("nls")
|
||||
public final class Constants {
|
||||
|
@ -465,6 +465,30 @@ public final class Constants {
|
|||
*/
|
||||
public static final String ATTR_BUILTIN_BINARY_MERGER = "binary"; //$NON-NLS-1$
|
||||
|
||||
/**
|
||||
* Null checker for a {@code @NonNull} parameter.
|
||||
*
|
||||
* <p>This is a briefer equivalent to
|
||||
* <pre>
|
||||
* if (arg == null) {
|
||||
* throw new NullPointerException();
|
||||
* }
|
||||
* </pre>
|
||||
* with the added benefit that it does not trigger nullness warnings when
|
||||
* {@code arg} is declared as {@code @NonNull}.
|
||||
*
|
||||
* @param arg a non-null object reference
|
||||
* @return arg
|
||||
* @throws NullPointerException if {@code arg} is null
|
||||
* @since 5.4
|
||||
*/
|
||||
public static <T> T checkNotNull(T arg) {
|
||||
if (arg == null) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
return arg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new digest function for objects.
|
||||
*
|
||||
|
|
Loading…
Reference in New Issue