Google Guava for cleaner code
Upcoming SlideShare
Loading in...5
×
 

Google Guava for cleaner code

on

  • 19,296 views

Presentation on JugMK event

Presentation on JugMK event

Statistics

Views

Total Views
19,296
Views on SlideShare
6,156
Embed Views
13,140

Actions

Likes
25
Downloads
182
Comments
0

16 Embeds 13,140

http://java.dzone.com 9613
http://blog.mitemitreski.com 3246
http://armandocouto.com.br 187
http://feeds.feedburner.com 39
http://3233503126001905087_4fd8d02b78378cb682cb3721c17a587ac0afbeb8.blogspot.com 28
http://rritw.com 5
http://translate.googleusercontent.com 4
https://www.google.de 4
http://webcache.googleusercontent.com 3
http://www.rritw.com 3
https://www.google.com 2
http://www.dzone.com 2
http://www.slashdocs.com 1
http://localhost 1
http://www.google.ca 1
http://www.google.com 1
More...

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Google Guava for cleaner code Google Guava for cleaner code Presentation Transcript

  • Cleaner code with Guava Code samples @ git://github.com/mitemitreski/guava-examples.git@mitemitreski08-02-2012
  • What is Guava?
  • 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
  • NULL"Null sucks." - Doug Lea "I call it my billion-dollar mistake." - C. A. R. Hoare Null is ambiguous if ( x != null && x.someM()!=null && ) {}
  • @Test public void optionalExample() { Optional<Integer> possible = Optional.of(3);// Makeoptional of given type possible.isPresent(); // returns true if nonNull possible.or(10); // returns this possible value ordefault possible.get(); // returns 3 }
  • @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); }
  • // all in (expression, format,message)public void somePreconditions() { checkNotNull(theUnknowMan.getId()); // Will throw NPE checkState(!theUnknowMan.isSick()); // Will throwIllegalStateException checkArgument(theUnknowMan.getAddress() != null, "We couldnt find the description for customer withid %s", theUnknowMan.getId()); }
  • JSR-305 Annotations for software defect detection@Nullable @NotNull1.javax.validation.constraints.NotNull - EE62.edu.umd.cs.findbugs.annotations.NonNull – Findbugs,Sonar3.javax.annotation.Nonnull – JSR-3054.com.intellij.annotations.NotNull - intelliJIDEAWhat to use and when?
  • Eclipse support
  • 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; }
  • 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; }
  • The Guava wayObjects.equal("a", "a"); //returns true JDK7Objects.equal(null, "a"); //returnsfalse Object.deepEquals(Object a, Object b)Objects.equal("a", null); //returns Object.equals(Object a, Object b)falseObjects.equal(null, null); //returnstrueObjects.hashCode(name,adress,url); Objects.hash(name,adress,url);  Objects.toStringHelper(this)        .add("x", 1)        .toString();
  • The Guava waypublic 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();   }
  • Common Primitives
  • Joiner/ Splitter
  • Character MatchersUse a predefined constant (examples) • CharMatcher.WHITESPACE (tracks Unicode defn.) • CharMatcher.JAVA_DIGIT • CharMatcher.ASCII • CharMatcher.ANYUse a factory method (examples) • CharMatcher.is(x) • CharMatcher.isNot(_) • CharMatcher.oneOf("aeiou").negate() • CharMatcher.inRange(a, z).or(inRange(A, Z))
  • Character MatchersString noControl =CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); // removecontrol 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 arent digits orlowercase
  • 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) throwsException { return retreveCustomerForKey(key); } });
  • importcom.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.)
  • 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!!!
  • 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! }
  • Filter collections Iterables SignatureCollection type Filter method boolean all(Iterable, Predicate)Iterable Iterables.filter(Iterable, Predicate) boolean any(Iterable, Predicate)Iterator Iterators.filter(Iterator, Predicate)Collection Collections2.filter(Collection, Predicate)T find(Iterable, Predicate)Set Sets.filter(Set, Predicate) removeIf(Iterable, Predicate)SortedSet Sets.filter(SortedSet, Predicate)Map Maps.filterKeys(Map, Predicate) Maps.filterValues(Map, Maps.filterEntrie Predicate)SortedMap Maps.filterKeys(SortedMap, Predicate)Maps.filterValues(SortedMap, Predicate) Maps.filterEntrieMultimap Multimaps.filterKeys(Multimap, Predicate) Multimaps.filterValues(Multimap, Predic Multimaps.filterE
  • Transform collectionsListMultimap<String, String> firstNameToLastNames;// maps first names to all last names of people with thatfirst nameListMultimap<String, String> firstNameToName =Multimaps.transformEntries(firstNameToLastNames,  new EntryTransformer<String, String, String> () {    public String transformEntry(String firstName, StringlastName) {      return firstName + " " + lastName;    }  });
  • Transform collectionsCollection type Transform methodIterable 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, EntryTransforSortedMap* Maps.transformValues(SortedMap, Function) Maps.transformEntries(SortedMap, EntryTr Multimaps.transformEntries(MulMultimap* Multimaps.transformValues(Multimap, Function) timap, EntryTransformer) Multimaps.transformValues(ListMultimap Multimaps.transformEntries(ListListMultimap* , Function) Multimap, EntryTransformer)Table Tables.transformValues(Table, Function)
  • 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);
  • Load resources
  • When to use Guava?• Temporary collections• Mutable collections• String Utils• Check if (x==null)• Always ?
  • When to use Guava?"I could just write that myself." But...•These things are much easier to mess up than itseems•With a library, other people will make your code fasterfor You•When you use a popular library, your code is in themainstream•When you find an improvement to your privatelibrary, howmany people did you help?Well argued in Effective Java 2e, Item 47.
  • Where can you use it ?•Java 5.0+ <dependency>     <groupId>com.google.guava</groupId>• GWT     <artifactId>guava</artifactId>     <version>10.0.1</version>•Android </dependency>