google guava for cleaner code

32
Cleaner code with Guava 08-02-2012 @mitemitreski Code samples @ git://github.com/mitemitreski/guava-examples.git

Upload: mite-mitreski

Post on 07-May-2015

21.316 views

Category:

Education


1 download

DESCRIPTION

Presentation on JugMK event

TRANSCRIPT

Page 1: Google Guava for cleaner code

Cleaner code with Guava

08-02-2012

@mitemitreski

Code samples @ git://github.com/mitemitreski/guava-examples.git

Page 2: Google Guava for cleaner code

What is Guava?

Page 3: Google Guava for cleaner code

What is Google Guava?

• com.google.common.annotation• com.google.common.base• com.google.common.collect• com.google.common.io• com.google.common.net• com.google.common.primitives• com.google.common.util.concurrent

Page 4: Google Guava for cleaner code

NULL

"Null sucks." - Doug Lea

"I call it my billion-dollar mistake." - C. A. R. Hoare

if ( x != null && x.someM()!=null && ) {}

Null is ambiguous

Page 5: Google Guava for cleaner code

@Test

public void optionalExample() {

Optional<Integer> possible = Optional.of(3);// Make optional of given type

possible.isPresent(); // returns true if nonNull

possible.or(10); // returns this possible value or default

possible.get(); // returns 3

}

Page 6: Google Guava for cleaner code
Page 7: Google Guava for cleaner code

@Test

public void testNeverNullWithoutGuava() {

Integer defaultId = null;

Integer id = theUnknowMan.getId() != null ? theUnknowMan.getId() : defaultId;

}

@Test(expected = NullPointerException.class)

public void testNeverNullWithGuava() {

Integer defaultId = null;

int id = Objects.firstNonNull(theUnknowMan.getId(), defaultId);

assertEquals(0, id);

}

Page 8: Google Guava for cleaner code
Page 9: Google Guava for cleaner code

// all in (expression, format,message)

public void somePreconditions() {

checkNotNull(theUnknowMan.getId()); // Will throw NPE

checkState(!theUnknowMan.isSick()); // Will throw IllegalStateException

checkArgument(theUnknowMan.getAddress() != null,

"We couldn't find the description for customer with id %s", theUnknowMan.getId());

}

Page 10: Google Guava for cleaner code

JSR-305 Annotations for software defect detection

@Nullable @NotNull

1.javax.validation.constraints.NotNull - EE6

2.edu.umd.cs.findbugs.annotations.NonNull – Findbugs, Sonar

3.javax.annotation.Nonnull – JSR-305

4.com.intellij.annotations.NotNull - intelliJIDEA

What to use and when?

Page 11: Google Guava for cleaner code

Eclipse support

Page 12: Google Guava for cleaner code

hashCode() and equals()

@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((adress == null) ? 0 : adress.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; }

Page 13: Google Guava for cleaner code

hashCode() and equals()

@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((adress == null) ? 0 : adress.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((url == null) ? 0 : url.hashCode()); return result; }

Page 14: Google Guava for cleaner code

The Guava way

Objects.equal("a", "a"); //returns trueObjects.equal(null, "a"); //returns falseObjects.equal("a", null); //returns falseObjects.equal(null, null); //returns true

Object.equals(Object a, Object b)

Object.deepEquals(Object a, Object b)

JDK7

Objects.hashCode(name,adress,url);

Objects.hash(name,adress,url);

 Objects.toStringHelper(this)       .add("x", 1)       .toString();

Page 15: Google Guava for cleaner code

The Guava way

public int compareTo(Foo that) {     return ComparisonChain.start()         .compare(this.aString, that.aString)         .compare(this.anInt, that.anInt)         .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())         .result();   }

Page 16: Google Guava for cleaner code

Common Primitives

Page 17: Google Guava for cleaner code

Joiner/ Splitter

Page 18: Google Guava for cleaner code

Character Matchers

Use a predefined constant (examples)• CharMatcher.WHITESPACE (tracks Unicode defn.)• CharMatcher.JAVA_DIGIT• CharMatcher.ASCII• CharMatcher.ANY

Use a factory method (examples)• CharMatcher.is('x')• CharMatcher.isNot('_')• CharMatcher.oneOf("aeiou").negate()• CharMatcher.inRange('a', 'z').or(inRange('A',

'Z'))

Page 19: Google Guava for cleaner code

Character Matchers

String noControl = CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); // remove control charactersString theDigits = CharMatcher.DIGIT.retainFrom(string); // only the digitsString lowerAndDigit = CharMatcher.or(CharMatcher.JAVA_DIGIT, CharMatcher.JAVA_LOWER_CASE).retainFrom(string);  // eliminate all characters that aren't digits or lowercase

Page 20: Google Guava for cleaner code

import com.google.common.cache.*;

Cache<Integer, Customer> cache = CacheBuilder.newBuilder() .weakKeys() .maximumSize(10000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(new CacheLoader<Integer, Customer>() {

@Override public Customer load(Integer key) throws Exception {

return retreveCustomerForKey(key); }

});

Page 21: Google Guava for cleaner code

import com.google.common.collect.*;

• Immutable Collections• Multimaps, Multisets, BiMaps… aka Google-

Collections• Comparator-related utilities• Stuff similar to Apache commons collections• Some functional programming support

(filter/transform/etc.)

Page 22: Google Guava for cleaner code

Functions and Predicates

Java 8 will support closures …

Function<String, Integer> lengthFunction = new Function<String, Integer>() {  public Integer apply(String string) {    return string.length();  }};Predicate<String> allCaps = new Predicate<String>() {  public boolean apply(String string) {    return CharMatcher.JAVA_UPPER_CASE.matchesAllOf(string);  }};

It is not recommended to overuse this!!!

Page 23: Google Guava for cleaner code

Filter collections

@Test public void filterAwayNullMapValues() { SortedMap<String, String> map = new TreeMap<String, String>(); map.put("1", "one"); map.put("2", "two"); map.put("3", null); map.put("4", "four"); SortedMap<String, String> filtered = SortedMaps.filterValues(map, Predicates.notNull()); assertThat(filtered.size(), is(3)); // null entry for "3" is gone! }

Page 24: Google Guava for cleaner code

Filter collectionsCollection type Filter method

Iterable Iterables.filter(Iterable, Predicate)

Iterator Iterators.filter(Iterator, Predicate)

Collection Collections2.filter(Collection, Predicate)

Set Sets.filter(Set, Predicate)

SortedSet Sets.filter(SortedSet, Predicate)

Map Maps.filterKeys(Map, Predicate) Maps.filterValues(Map, Predicate)Maps.filterEntries(Map, Predicate)

SortedMap Maps.filterKeys(SortedMap, Predicate)Maps.filterValues(SortedMap, Predicate)Maps.filterEntries(SortedMap, Predicate)

Multimap Multimaps.filterKeys(Multimap, Predicate)Multimaps.filterValues(Multimap, Predicate)Multimaps.filterEntries(Multimap, Predicate)

Iterables Signature

boolean all(Iterable, Predicate)

boolean any(Iterable, Predicate)

T find(Iterable, Predicate)

removeIf(Iterable, Predicate)

Page 25: Google Guava for cleaner code

Transform collectionsListMultimap<String, String> firstNameToLastNames;// maps first names to all last names of people with that first name

ListMultimap<String, String> firstNameToName = Multimaps.transformEntries(firstNameToLastNames,  new EntryTransformer<String, String, String> () {    public String transformEntry(String firstName, String lastName) {      return firstName + " " + lastName;    }  });

Page 26: Google Guava for cleaner code

Transform collections

Collection type Transform method

Iterable Iterables.transform(Iterable, Function)

Iterator Iterators.transform(Iterator, Function)

Collection Collections2.transform(Collection, Function)

List Lists.transform(List, Function)

Map* Maps.transformValues(Map, Function) Maps.transformEntries(Map, EntryTransformer)

SortedMap* Maps.transformValues(SortedMap, Function)Maps.transformEntries(SortedMap, EntryTransformer)

Multimap* Multimaps.transformValues(Multimap, Function)Multimaps.transformEntries(Multimap, EntryTransformer)

ListMultimap* Multimaps.transformValues(ListMultimap, Function)

Multimaps.transformEntries(ListMultimap, EntryTransformer)

Table Tables.transformValues(Table, Function)

Page 27: Google Guava for cleaner code

Collection goodies

// oldway Map<String, Map<Long, List<String>>> mapOld = new HashMap<String, Map<Long, List<String>>>(); // the guava way Map<String, Map<Long, List<String>>> map = Maps.newHashMap(); // list ImmutableList<String> of = ImmutableList.of("a", "b", "c"); // Same one for map ImmutableMap<String, String> map = ImmutableMap.of("key1", "value1", "key2", "value2"); //list of ints List<Integer> theList = Ints.asList(1, 2, 3, 4, 522, 5, 6);

Page 28: Google Guava for cleaner code

Load resources

Page 29: Google Guava for cleaner code

When to use Guava?

• Temporary collections

• Mutable collections

• String Utils

• Check if (x==null)

• Always ?

Page 30: Google Guava for cleaner code

When to use Guava?

"I could just write that myself." But...

•These things are much easier to mess up than it seems

•With a library, other people will make your code faster for You

•When you use a popular library, your code is in the

mainstream

•When you find an improvement to your private library, how

many people did you help?

Well argued in Effective Java 2e, Item 47.

Page 31: Google Guava for cleaner code

Where can you use it ?

•Java 5.0+

• GWT

•Android

<dependency>    <groupId>com.google.guava</groupId>    <artifactId>guava</artifactId>    <version>10.0.1</version></dependency>

Page 32: Google Guava for cleaner code