Skip to content

Instantly share code, notes, and snippets.

@winstonewert
Created February 20, 2016 03:16
Show Gist options
  • Save winstonewert/b8c5becaff623221b667 to your computer and use it in GitHub Desktop.
Save winstonewert/b8c5becaff623221b667 to your computer and use it in GitHub Desktop.
NotEmptyList<T> getItems(); // always has at least one element.
List<T> maybeGetItems(); // might have zero elements.
T average(NotEmptyList<T> items) {
T value = 0;
for (T item: items.get()) {
value += item;
}
return value / items.get().size();
}
println(average(getItems()));
List<T> myItems = maybeGetItems();
if (myItems.isEmpty()) {
println("No items");
} else{
println(average(NonEmptyList.of(myItems)));
}
FoobarSource getFoobarSource(); // never returns NULL
FoobarSource maybeGetFoobarSource(); // might return NULL
int foobar(FoobarSource source) {
return source.foo() + source.bar();
}
println(foobar(getFoobarSource()));
FoobarSource foobarSource = maybeGetFoobarSource();
if (foobarSource != null) {
println(foobar(foobarSource));
}
FoobarSource getFoobarSource(); // never returns NULL
Optional<FoobarSource> maybeGetFoobarSource();
int foobar(FoobarSource source) {
return source.foo() + source.bar();
}
println(foobar(getFoobarSource()));
FoobarSource foobarSource = maybeGetFoobarSource();
if (foobarSource.isPresent()) {
println(foobar(foobarSource.get()));
}
List<T> getItems(); // always has at least one element.
List<T> maybeGetItems(); // might have zero elements.
T average(List<T> items) {
T value = 0;
for (T item: items) {
value += item;
}
return value / items.size();
}
println(average(getItems()));
List<T> myItems = maybeGetItems();
if (myItems.isEmpty()) {
println("No items");
} else{
println(average(myItems));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment