SlideShare a Scribd company logo
1 of 32
Download to read offline
Cleaner code with Guava

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




@mitemitreski
08-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);// Make
optional of given type
     possible.isPresent(); // returns true if nonNull
    possible.or(10); // returns this possible value or
default
     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 throw
IllegalStateException
     checkArgument(theUnknowMan.getAddress() != null,
        "We couldn't find the description for customer with
id %s", theUnknowMan.getId());
 }
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?
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 way
Objects.equal("a", "a"); //returns true      JDK7
Objects.equal(null, "a"); //returns
false                                   Object.deepEquals(Object a, Object b)
Objects.equal("a", null); //returns     Object.equals(Object a, Object b)
false
Objects.equal(null, null); //returns
true
Objects.hashCode(name,adress,url);      Objects.hash(name,adress,url);



  Objects.toStringHelper(this)
        .add("x", 1)
        .toString();
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();
   }
Common Primitives
Joiner/ Splitter
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'))
Character Matchers
String noControl =
CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); // remove
control characters
String theDigits = CharMatcher.DIGIT.retainFrom(string); //
only the digits
String lowerAndDigit =
CharMatcher.or(CharMatcher.JAVA_DIGIT,
CharMatcher.JAVA_LOWER_CASE).retainFrom(string);
  // eliminate all characters that aren't digits or
lowercase
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);
         }

       });
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.)
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 Signature
Collection 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.filterEntrie



Multimap       Multimaps.filterKeys(Multimap, Predicate)
                                                    Multimaps.filterValues(Multimap, Predic
                                                                           Multimaps.filterE
Transform collections
ListMultimap<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;
    }
  });
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, EntryTransfor

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

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

                  Multimaps.transformValues(ListMultimap Multimaps.transformEntries(List
ListMultimap*
                  , 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 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.
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>
Google Guava for cleaner code

More Related Content

What's hot

What's hot (20)

Introducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data ScienceIntroducing DataFrames in Spark for Large Scale Data Science
Introducing DataFrames in Spark for Large Scale Data Science
 
Functional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User GroupFunctional Patterns with Java8 @Bucharest Java User Group
Functional Patterns with Java8 @Bucharest Java User Group
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache CalciteCost-based Query Optimization in Apache Phoenix using Apache Calcite
Cost-based Query Optimization in Apache Phoenix using Apache Calcite
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Hive 3 - a new horizon
Hive 3 - a new horizonHive 3 - a new horizon
Hive 3 - a new horizon
 
Introduction to regular expressions
Introduction to regular expressionsIntroduction to regular expressions
Introduction to regular expressions
 
Sql
SqlSql
Sql
 
Bulk Loading Data into Cassandra
Bulk Loading Data into CassandraBulk Loading Data into Cassandra
Bulk Loading Data into Cassandra
 
Bulk Loading into Cassandra
Bulk Loading into CassandraBulk Loading into Cassandra
Bulk Loading into Cassandra
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Data Warehouse (ETL) testing process
Data Warehouse (ETL) testing processData Warehouse (ETL) testing process
Data Warehouse (ETL) testing process
 
JDBC
JDBCJDBC
JDBC
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)Hibernate start (하이버네이트 시작하기)
Hibernate start (하이버네이트 시작하기)
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 

Viewers also liked

Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon Berlin
 
DE000010063015B4_all_pages
DE000010063015B4_all_pagesDE000010063015B4_all_pages
DE000010063015B4_all_pages
Dr. Ingo Dahm
 
Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002
rosemere12
 
Career Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 FinalCareer Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 Final
Victoria Pazukha
 
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
rtemerson
 
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Cagliostro Puntodue
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
Mite Mitreski
 
LESS CSS Processor
LESS CSS ProcessorLESS CSS Processor
LESS CSS Processor
sdhoman
 

Viewers also liked (20)

Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...
 
Introduction to rx java for android
Introduction to rx java for androidIntroduction to rx java for android
Introduction to rx java for android
 
자바8 람다식 소개
자바8 람다식 소개자바8 람다식 소개
자바8 람다식 소개
 
AVG Android App Performance Report by AVG Technologies
AVG Android App Performance Report by AVG TechnologiesAVG Android App Performance Report by AVG Technologies
AVG Android App Performance Report by AVG Technologies
 
DE000010063015B4_all_pages
DE000010063015B4_all_pagesDE000010063015B4_all_pages
DE000010063015B4_all_pages
 
World Tech E S
World Tech  E SWorld Tech  E S
World Tech E S
 
Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002Curso de idiomas globo inglês livro002
Curso de idiomas globo inglês livro002
 
El ROI no es negociable - Marketing Digital para Startups - Parte 3
 El ROI no es negociable - Marketing Digital para Startups - Parte 3 El ROI no es negociable - Marketing Digital para Startups - Parte 3
El ROI no es negociable - Marketing Digital para Startups - Parte 3
 
Career Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 FinalCareer Mobility Itp Conference2011 Final
Career Mobility Itp Conference2011 Final
 
Canjs
CanjsCanjs
Canjs
 
Interstellar Designs
Interstellar DesignsInterstellar Designs
Interstellar Designs
 
Reading and writing a massive online hypertext - Meetup session 3
Reading and writing a massive online hypertext - Meetup session 3Reading and writing a massive online hypertext - Meetup session 3
Reading and writing a massive online hypertext - Meetup session 3
 
Real world citizenship
Real world citizenshipReal world citizenship
Real world citizenship
 
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
Introductory Webinar: Getting Diverse Butts...why? The DWC Group_7.11
 
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
Prestazioni sanitarie-la-giungla-delle-tariffe-test-salute-89
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
LESS CSS Processor
LESS CSS ProcessorLESS CSS Processor
LESS CSS Processor
 

Similar to Google Guava for cleaner code

Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
shinolajla
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 

Similar to Google Guava for cleaner code (20)

Google collections api an introduction
Google collections api   an introductionGoogle collections api   an introduction
Google collections api an introduction
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Monads in javascript
Monads in javascriptMonads in javascript
Monads in javascript
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Groovy
GroovyGroovy
Groovy
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Miracle of std lib
Miracle of std libMiracle of std lib
Miracle of std lib
 
An Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQLAn Exploration of the Formal Properties of PromQL
An Exploration of the Formal Properties of PromQL
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
GeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheetGeoGebra JavaScript CheatSheet
GeoGebra JavaScript CheatSheet
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 

More from Mite Mitreski

Java2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integrationJava2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integration
Mite Mitreski
 
Eclipse 10 years Party
Eclipse 10 years PartyEclipse 10 years Party
Eclipse 10 years Party
Mite Mitreski
 

More from Mite Mitreski (8)

Getting all the 99.99(9) you always wanted
Getting all the 99.99(9) you always wanted Getting all the 99.99(9) you always wanted
Getting all the 99.99(9) you always wanted
 
Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015
 
Devoxx 2014 : Sparky guide to bug free JavaScirpt
Devoxx 2014 : Sparky guide to bug free JavaScirptDevoxx 2014 : Sparky guide to bug free JavaScirpt
Devoxx 2014 : Sparky guide to bug free JavaScirpt
 
Microservice pitfalls
Microservice pitfalls Microservice pitfalls
Microservice pitfalls
 
Unix for developers
Unix for developersUnix for developers
Unix for developers
 
State of the lambda
State of the lambdaState of the lambda
State of the lambda
 
Java2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integrationJava2day 2013 : Modern workflows for javascript integration
Java2day 2013 : Modern workflows for javascript integration
 
Eclipse 10 years Party
Eclipse 10 years PartyEclipse 10 years Party
Eclipse 10 years Party
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 

Google Guava for cleaner code

  • 1. Cleaner code with Guava Code samples @ git://github.com/mitemitreski/guava-examples.git @mitemitreski 08-02-2012
  • 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. 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. @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 }
  • 6.
  • 7. @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); }
  • 8.
  • 9. // 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()); }
  • 10. 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?
  • 12. 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; }
  • 13. 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; }
  • 14. The Guava way Objects.equal("a", "a"); //returns true JDK7 Objects.equal(null, "a"); //returns false Object.deepEquals(Object a, Object b) Objects.equal("a", null); //returns Object.equals(Object a, Object b) false Objects.equal(null, null); //returns true Objects.hashCode(name,adress,url); Objects.hash(name,adress,url);  Objects.toStringHelper(this)        .add("x", 1)        .toString();
  • 15. 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();    }
  • 18. 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'))
  • 19. Character Matchers String noControl = CharMatcher.JAVA_ISO_CONTROL.removeFrom(string); // remove control characters String theDigits = CharMatcher.DIGIT.retainFrom(string); // only the digits String lowerAndDigit = CharMatcher.or(CharMatcher.JAVA_DIGIT, CharMatcher.JAVA_LOWER_CASE).retainFrom(string);   // eliminate all characters that aren't digits or lowercase
  • 20. 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); } });
  • 21. 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.)
  • 22. 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!!!
  • 23. 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! }
  • 24. Filter collections Iterables Signature Collection 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.filterEntrie Multimap Multimaps.filterKeys(Multimap, Predicate) Multimaps.filterValues(Multimap, Predic Multimaps.filterE
  • 25. Transform collections ListMultimap<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;     }   });
  • 26. 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, EntryTransfor SortedMap* Maps.transformValues(SortedMap, Function) Maps.transformEntries(SortedMap, EntryTr Multimaps.transformEntries(Mul Multimap* Multimaps.transformValues(Multimap, Function) timap, EntryTransformer) Multimaps.transformValues(ListMultimap Multimaps.transformEntries(List ListMultimap* , Function) Multimap, EntryTransformer) Table Tables.transformValues(Table, Function)
  • 27. 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);
  • 29. When to use Guava? • Temporary collections • Mutable collections • String Utils • Check if (x==null) • Always ?
  • 30. 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.
  • 31. 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>