Skip to content

Instantly share code, notes, and snippets.

@jburwell
Last active July 23, 2018 16:36
Show Gist options
  • Save jburwell/2b4a241f3165ff964acc84bd1ddf64e6 to your computer and use it in GitHub Desktop.
Save jburwell/2b4a241f3165ff964acc84bd1ddf64e6 to your computer and use it in GitHub Desktop.
Guava Idioms

This gist is a small demonstration of using Guava's Preconditions class to more concisely express preconditions and assertions. Often, methods and constructors have stanzas such as the following declared:

public static boolean doSomething(final Object param1, final Object param2) {

    if (param1 == null) {
        throw InvalidArgumentException("doSomething requires a non-null value for param1");
    }
    
    if (param2 == null) {
        throw InvalidArgumentException("doSomething requires a non-null value for param2");
    }
    
    // do work ...
    
}

The checkArgument and checkState methods shorten these checks.

N.B. This could be further simplified by introducing two additional utility methods wrapping checkArgument -- checkArgumentNotNull and checkArgumentNotBlank.

package net.cockamamy.playpen.utils;
import static java.lang.String.format;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
public final class Files {
public static File openFile(final File aParentDirectory, final String aFileName) {
checkArgument(aParentDirectory != null, format(
"%1$s.createFile requires a non-null parent directory.",
FileUtilities.class.getName()));
checkArgument(isNotBlank(aFileName) : format(
"%1$s.createFile requires a non-blank file name.",
FileUtilities.class.getName()));
final File aFile = new File(aParentDirectory, aFileName);
checkState(!aFile.exists(), format(
"%1$s does not contain %2$s", aParentDirectory.getName(),
aFileName)));
return aFile;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment