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...
NULL"Null sucks." - Doug Lea                                       "I call it my billion-dollar                           ...
@Test public void optionalExample() {    Optional<Integer> possible = Optional.of(3);// Makeoptional of given type     pos...
@Test public void testNeverNullWithoutGuava() {     Integer defaultId = null;    Integer id = theUnknowMan.getId() != null...
// all   in (expression, format,message)public void somePreconditions() {     checkNotNull(theUnknowMan.getId()); // Will ...
JSR-305 Annotations for software defect detection@Nullable @NotNull1.javax.validation.constraints.NotNull - EE62.edu.umd.c...
Eclipse support
hashCode() and equals()@Override  public int hashCode() {    final int prime = 31;    int result = 1;    result = prime * ...
hashCode() and equals()@Override  public int hashCode() {    final int prime = 31;    int result = 1;    result = prime * ...
The Guava wayObjects.equal("a", "a"); //returns true      JDK7Objects.equal(null, "a"); //returnsfalse                    ...
The Guava waypublic int compareTo(Foo that) {     return ComparisonChain.start()         .compare(this.aString, that.aStri...
Common Primitives
Joiner/ Splitter
Character MatchersUse a predefined constant (examples)   • CharMatcher.WHITESPACE (tracks Unicode defn.)   • CharMatcher.J...
Character MatchersString noControl =CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); // removecontrol charactersString the...
import com.google.common.cache.*;    Cache<Integer, Customer> cache =CacheBuilder.newBuilder()        .weakKeys()        ....
importcom.google.common.collect.*;• Immutable Collections• Multimaps, Multisets, BiMaps… aka Google-  Collections• Compara...
Functions and Predicates     Java 8 will support closures …Function<String, Integer> lengthFunction = new Function<String,...
Filter collections @Test  public void filterAwayNullMapValues() {    SortedMap<String, String> map = new TreeMap<String,St...
Filter collections                                                           Iterables SignatureCollection type Filter met...
Transform collectionsListMultimap<String, String> firstNameToLastNames;// maps first names to all last names of people wit...
Transform collectionsCollection type   Transform methodIterable          Iterables.transform(Iterable, Function)Iterator  ...
Collection goodies    // oldway    Map<String, Map<Long, List<String>>> mapOld =    new HashMap<String, Map<Long, List<Str...
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 lib...
Where can you use it ?•Java 5.0+          <dependency>                        <groupId>com.google.guava</groupId>• GWT    ...
Google Guava for cleaner code
Google Guava for cleaner code
Google Guava for cleaner code
Upcoming SlideShare
Loading in...5
×

Google Guava for cleaner code

22,040

Published on

Presentation on JugMK event

Published in: Education, Technology, Business
0 Comments
30 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
22,040
On Slideshare
0
From Embeds
0
Number of Embeds
16
Actions
Shares
0
Downloads
236
Comments
0
Likes
30
Embeds 0
No embeds

No notes for slide

Google Guava for cleaner code

  1. 1. Cleaner code with Guava Code samples @ git://github.com/mitemitreski/guava-examples.git@mitemitreski08-02-2012
  2. 2. What is Guava?
  3. 3. 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
  4. 4. 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 && ) {}
  5. 5. @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 }
  6. 6. @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); }
  7. 7. // 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()); }
  8. 8. 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?
  9. 9. Eclipse support
  10. 10. 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; }
  11. 11. 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; }
  12. 12. 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();
  13. 13. 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();   }
  14. 14. Common Primitives
  15. 15. Joiner/ Splitter
  16. 16. 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))
  17. 17. 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
  18. 18. 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); } });
  19. 19. 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.)
  20. 20. 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!!!
  21. 21. 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! }
  22. 22. 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
  23. 23. 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;    }  });
  24. 24. 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)
  25. 25. 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);
  26. 26. Load resources
  27. 27. When to use Guava?• Temporary collections• Mutable collections• String Utils• Check if (x==null)• Always ?
  28. 28. 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.
  29. 29. 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>
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×