SlideShare a Scribd company logo
1 of 27
Download to read offline
Google Guava
           Thomas Ferris Nicolaisen
                  @tfnico
              www.tfnico.com

Code at http://github.com/tfnico/guava-examples
So much goodness in here...

• 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
import com.google.common.annotations.*;
/**
 * An annotation that indicates that the visibility of a type or member has
 * been relaxed to make the code testable.
 *
 */
public @interface VisibleForTesting




      /**
       * Use this method for determining that a cart item is eligible for retail
  pickup.
       *
       * @param item with productClass PRINT, or exportName "INDEXPRINT"
       * @return true if it is allowed, false if not
       */
      @VisibleForTesting
      static boolean allowedForRetailPickup(final CartItem item) {
          ...
import com.google.common.base.*;

   @Test
   public void charSetsAndDefaults()
   {
       // Here's some charsets
       Charset utf8 = Charsets.UTF_8;
       assertTrue(utf8.canEncode());

       // Primitive defaults:
       Integer defaultValue = Defaults.defaultValue(int.class);
       assertEquals(0, defaultValue.intValue());
   }
import com.google.common.base.*;

@Test
public void equalityAndIdentity()
{
	 //These could be useful for building equals methods
    assertFalse(Equivalences.equals().equivalent("you", null));
    assertTrue(Equivalences.identity().equivalent("hey", "hey"));
}
import com.google.common.base.*;

 @Test
 public void joinSomeStrings()
 {
     ImmutableSet<String> strings = ImmutableSet.of("A", "B", "C");

     String joined = Joiner.on(":").join(strings);
     assertEquals("A:B:C", joined);
 }
import com.google.common.base.*;
@Test
public void splitSomeStrings()
{
    String string = "A:B:C";

    String[] parts = string.split(":"); //the old way
    String backTogether = Joiner.on(":").join(parts);
    assertEquals(string, backTogether);

    String gorbleString = ": A::: B : C :::";
    Iterable<String> gorbleParts = Splitter.on(":")
       .omitEmptyStrings().trimResults().split(gorbleString);
    String gorbleBackTogether = Joiner.on(":").join(gorbleParts);
    assertEquals(string, gorbleBackTogether); // A:B:C
}
import com.google.common.base.*;
@Test
public void moreFunWithStrings()
{
    assertNull(Strings.emptyToNull(""));
    assertEquals("", Strings.nullToEmpty(null));

    // About the only thing we ever used in commons-lang? :)
     assertTrue(Strings.isNullOrEmpty(""));

    assertEquals("oioioi", Strings.repeat("oi", 3));
    assertEquals("Too short      ", Strings.padEnd("Too short", 15, '
}
//Some customers
Customer bob = new Customer(1, "Bob");
Customer lisa = new Customer(2, "Lisa");
Customer stephen = new Customer(3, "Stephen");
Customer ken = new Customer(null,"Ken");
import com.google.common.base.*;
  @Test
  public void toStringsAndHashcodes()
  {
      Object[] bobAndLisa = new Object[] { bob, lisa };

      // Make some hashcode!
      int hashCode = Objects.hashCode(bob, lisa);

      assertEquals(Arrays.hashCode(bobAndLisa), hashCode);

      // Build toString method
      String string = Objects.toStringHelper(bob)
              .add("name", bob.getName())
              .add("id", bob.getId()).toString();
      assertEquals("Customer{name=Bob, id=1}", string);
  }
import com.google.common.base.*;

 @Test(expected = NullPointerException.class)
 public void needAnIntegerWhichIsNeverNull()
 {
   Integer defaultId = null;
   Integer kensId = ken.getId() != null ? ken.getId() : defaultId;
      // this one does not throw!

     int kensId2 = Objects.firstNonNull(ken.getId(), defaultId);
     assertEquals(0, kensId2);
     // But the above does!
 }
import com.google.common.base.*;


@Test(expected = IllegalArgumentException.class)
public void somePreconditions()
{
    // Pretend this is a constructor:
    Preconditions.checkNotNull(lisa.getId()); // Will throw NPE
    Preconditions.checkState(!lisa.isSick()); // Will throw ILE
    Preconditions.checkArgument(lisa.getAddress() != null,
        "No description for customer with id %s",lisa.getId());
}
import com.google.common.base.*;
 @Test
 public void fancierFunctions()
 {
     Function<Customer, Boolean> isCustomerWithOddId
     = new Function<Customer, Boolean>()
        {
         public Boolean apply(Customer customer)
        {
             return customer.getId().intValue() % 2 != 0;
         }
     };

     assertTrue(isCustomerWithOddId.apply(bob));
     assertFalse(isCustomerWithOddId.apply(lisa));

     // Functions are great for higher-order functions, like
     // project/transform, and fold
 }
import com.google.common.base.*;

@Test
public void somePredicates()
{
    ImmutableSet<Customer> customers =
      ImmutableSet.of(bob, lisa, stephen);

    Predicate<Customer> itsBob = Predicates.equalTo(bob);
    Predicate<Customer> itsLisa = Predicates.equalTo(lisa);
    Predicate<Customer> bobOrLisa = Predicates.or(itsBob, itsLisa);

// Predicates are great to pass in to higher-order functions
// like filter/search
    Iterable<Customer> filtered = Iterables.filter(customers, bobOrLisa
    assertEquals(2, ImmutableSet.copyOf(filtered).size());
}
import com.google.common.base.*;
 @Test
public void someSuppliers()
 {
 	 //Imagine we have Supploer that produces ingredients
 	 IngredientsFactory ingredientsFactory = new IngredientsFactory();
	 	
	 //A function 'bake' - (see next slide)
	 bake();
	
	 //Then it's pretty easy to get a Factory that bakes cakes :)
	 Supplier<Cake> cakeFactory =
       Suppliers.compose(bake(), ingredientsFactory);
	 cakeFactory.get();
	 cakeFactory.get();
	 cakeFactory.get();
	
	 assertEquals(3, ingredientsFactory.getNumberOfIngredientsUsed());
}
import com.google.common.base.*;


 	   private Function<Ingredients, Cake> bake() {
 	   	 return new Function<Ingredients, Cake>() {
 	   	 	 public Cake apply(Ingredients ingredients) {
 	   	 	 	 return new Cake(ingredients);
 	   	 	 }
 	   	 };
 	   }
import com.google.common.base.*;
@Test
public void someThrowables()
{
	
try
	
{
	
	    try{
	
	    	    Integer.parseInt("abc");
	
	    }
	
	    catch(RuntimeException e){
	
	    	    if(e instanceof ClassCastException) throw e; //old-style
	
	    	    Throwables.propagateIfInstanceOf(e, NumberFormatException.class); //the same
	
	    	    Throwables.propagateIfPossible(e); // Propagates if it is Error or RuntimeException
	
	    	    try {
	    	    	   	    Throwables.throwCause(e, true);
	    	    	   } catch (Exception e1) {
	    	    	   	    Throwables.propagate(e1); //Wraps if its a checked exception,
                                             //or lets it flow if not
	    	    	   }
	
	    }
	
}
	
catch(RuntimeException e){
	
	    Throwables.getCausalChain(e);
	
	    Throwables.getRootCause(e);
	
	    Throwables.getStackTraceAsString(e);
	
}
import com.google.common.base.*;
     @Test
	   public void someEnums()
     {
     	 assertEquals("UNDER_DOG",
           CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE,
                  "underDog"));
     	
     	 //Controlling services
     	 Service service = new FunkyService();
     	 service.start();
     	 assertEquals(Service.State.RUNNING, service.state());
        service.stop();
	   }
import com.google.common.collect.*;


@Test
public void someSets()
{
	 ImmutableSet<Customer> customers1 =
       ImmutableSet.of(bob, lisa, stephen);
	 ImmutableSet<Customer> customers2 =
        ImmutableSet.of(stephen, ken);
	
	 assertEquals(4, Sets.union(customers1, customers2).size());
	
	 assertEquals(ImmutableSet.of(stephen),
      Sets.intersection(customers1, customers2));
}
import com.google.common.collect.*;

@Test(expected=NullPointerException.class)
public void someConstraints()
{
    //instead of new HashSet<Customer>()
	 HashSet<Customer> customers = Sets.newHashSet();
	 customers.add(null); //this works. But should it?
	
	 Set<Customer> noMoreNulls =
       Constraints.constrainedSet(customers, Constraints.notNull());
	 noMoreNulls.add(null); //boom!
}
import com.google.common.io.*;

	   @Test
	   public void messAroundWithFile()
	   {
	   	   File file = new File("woop.txt");
	   	   try {
	   	   	    Files.touch(file);
	   	   	
	   	   	    Files.write("Hey sailor!", file, Charsets.UTF_8);
	   	   	
	   	   	    //Breakpoint here.. have a look at the file..
	   	   	
	   	   	    Files.toByteArray(file);
	   	   	    Files.newInputStreamSupplier(file);
	   	   	    assertEquals("Hey sailor!", Files.readFirstLine(file, Charsets.UTF_8));
	   	   	    assertEquals("Hey sailor!", Files.toString(file, Charsets.UTF_8));
	   	
	   	   	    Files.deleteRecursively(file);
	   	   	
	   	   } catch (IOException e) {
	   	   	    Throwables.propagate(e);
	   	   }
	   }
import com.google.common.io.*;


@Test
public void closingAndFlushing()
{
	 InputStream inputStream = System.in;
	 try {
	 	 inputStream.close();//The old way
	 } catch (IOException e) {
	 	 Throwables.propagate(e);
	 }
	 Closeables.closeQuietly(inputStream ); //The new way
	
	 //Or flush:
	 PrintStream outputStream = System.out;
	 Flushables.flushQuietly(outputStream);
}
import com.google.common.io.*;


@Test
public void classPathResources()
{
	 //This:
	 Resources.getResource("com/tfnico/examples/guava/BaseTest.class");
	
	 //instead of this:
	 String location = "com/tfnico/examples/guava/BaseTest.class";
   URL resource2 =
          this.getClass().getClassLoader().getResource(location);
	 Preconditions.checkArgument(resource2!=null,
        "resource %s not found", location);
}
import com.google.common.net.InetAddresses;

	    @Test
	    public void iNetAddressIsFixed()
	    {
	    	   try {
	    	   	
	    	   	    /**
	    	   	     * Unlike InetAddress.getByName(),
	    	   	     * the methods of this class never cause DNS services to be accessed.
	    	   	     * For this reason, you should prefer these methods as much as possible
	    	   	     * over their JDK equivalents whenever you are expecting to handle only
	    	   	     * IP address string literals -- there is no blocking DNS penalty for
	    	   	     * a malformed string.
	    	   	     */
	    	   	    InetAddresses.forString("0.0.0.0");
	    	   	
	    	   	    //Instead of this...
	    	   	    InetAddress.getByName("0.0.0.0");
	    	   	
	    	   } catch (UnknownHostException e) {
	    	   	    Throwables.propagate(e);
	    	   }
	    }
TODO
              (For this presentation)
•   Show off primitives

•   Show off CharMatcher

•   Add more collection examples

•   Add more higher order functions

•   Do concurrency stuff

•   Do cooler io stuff

•   Find patterns of old code that can be replaced
When to think Guava?

• For loops
• Temporary collections
• Mutable collections
• if( x == null)
• In short: method complexity
Arright, let’s try!

More Related Content

What's hot

Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix itRafael Dohms
 
Simple callcenter platform with PHP
Simple callcenter platform with PHPSimple callcenter platform with PHP
Simple callcenter platform with PHPMorten Amundsen
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactionsHusain Dalal
 
Modern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesModern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesMarkus Winand
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agentsRafael Winterhalter
 
C* Summit 2013: The World's Next Top Data Model by Patrick McFadin
C* Summit 2013: The World's Next Top Data Model by Patrick McFadinC* Summit 2013: The World's Next Top Data Model by Patrick McFadin
C* Summit 2013: The World's Next Top Data Model by Patrick McFadinDataStax Academy
 
Cassandra concepts, patterns and anti-patterns
Cassandra concepts, patterns and anti-patternsCassandra concepts, patterns and anti-patterns
Cassandra concepts, patterns and anti-patternsDave Gardner
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...Philip Schwarz
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't FreeKelley Robinson
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionsaber tabatabaee
 
VLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-StoresVLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-StoresDaniel Abadi
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlinintelliyole
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORMSaurabh Dixit
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 

What's hot (20)

Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Simple callcenter platform with PHP
Simple callcenter platform with PHPSimple callcenter platform with PHP
Simple callcenter platform with PHP
 
Grails transactions
Grails   transactionsGrails   transactions
Grails transactions
 
Modern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesModern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial Databases
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Sql query patterns, optimized
Sql query patterns, optimizedSql query patterns, optimized
Sql query patterns, optimized
 
Models for hierarchical data
Models for hierarchical dataModels for hierarchical data
Models for hierarchical data
 
C* Summit 2013: The World's Next Top Data Model by Patrick McFadin
C* Summit 2013: The World's Next Top Data Model by Patrick McFadinC* Summit 2013: The World's Next Top Data Model by Patrick McFadin
C* Summit 2013: The World's Next Top Data Model by Patrick McFadin
 
Cassandra concepts, patterns and anti-patterns
Cassandra concepts, patterns and anti-patternsCassandra concepts, patterns and anti-patterns
Cassandra concepts, patterns and anti-patterns
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...Sum and Product Types -The Fruit Salad & Fruit Snack Example - From F# to Ha...
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
VLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-StoresVLDB 2009 Tutorial on Column-Stores
VLDB 2009 Tutorial on Column-Stores
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Grails object relational mapping: GORM
Grails object relational mapping: GORMGrails object relational mapping: GORM
Grails object relational mapping: GORM
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 

Similar to Google guava

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code EffectivelyAndres Almiray
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Andres Almiray
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4jeresig
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsTomek Kaczanowski
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate BustersHamletDRC
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDBartłomiej Kiełbasa
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxcelenarouzie
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsTomek Kaczanowski
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
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 GuavaMite Mitreski
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014Guillaume POTIER
 

Similar to Google guava (20)

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Testing Java Code Effectively
Testing Java Code EffectivelyTesting Java Code Effectively
Testing Java Code Effectively
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17Testing Java Code Effectively - BaselOne17
Testing Java Code Effectively - BaselOne17
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Java Boilerplate Busters
Java Boilerplate BustersJava Boilerplate Busters
Java Boilerplate Busters
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
GoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDDGoCracow #5 Bartlomiej klimczak - GoBDD
GoCracow #5 Bartlomiej klimczak - GoBDD
 
VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
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
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 

Recently uploaded

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Google guava

  • 1. Google Guava Thomas Ferris Nicolaisen @tfnico www.tfnico.com Code at http://github.com/tfnico/guava-examples
  • 2. So much goodness in here... • 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
  • 3. import com.google.common.annotations.*; /** * An annotation that indicates that the visibility of a type or member has * been relaxed to make the code testable. * */ public @interface VisibleForTesting /** * Use this method for determining that a cart item is eligible for retail pickup. * * @param item with productClass PRINT, or exportName "INDEXPRINT" * @return true if it is allowed, false if not */ @VisibleForTesting static boolean allowedForRetailPickup(final CartItem item) { ...
  • 4. import com.google.common.base.*; @Test public void charSetsAndDefaults() { // Here's some charsets Charset utf8 = Charsets.UTF_8; assertTrue(utf8.canEncode()); // Primitive defaults: Integer defaultValue = Defaults.defaultValue(int.class); assertEquals(0, defaultValue.intValue()); }
  • 5. import com.google.common.base.*; @Test public void equalityAndIdentity() { //These could be useful for building equals methods assertFalse(Equivalences.equals().equivalent("you", null)); assertTrue(Equivalences.identity().equivalent("hey", "hey")); }
  • 6. import com.google.common.base.*; @Test public void joinSomeStrings() { ImmutableSet<String> strings = ImmutableSet.of("A", "B", "C"); String joined = Joiner.on(":").join(strings); assertEquals("A:B:C", joined); }
  • 7. import com.google.common.base.*; @Test public void splitSomeStrings() { String string = "A:B:C"; String[] parts = string.split(":"); //the old way String backTogether = Joiner.on(":").join(parts); assertEquals(string, backTogether); String gorbleString = ": A::: B : C :::"; Iterable<String> gorbleParts = Splitter.on(":") .omitEmptyStrings().trimResults().split(gorbleString); String gorbleBackTogether = Joiner.on(":").join(gorbleParts); assertEquals(string, gorbleBackTogether); // A:B:C }
  • 8. import com.google.common.base.*; @Test public void moreFunWithStrings() { assertNull(Strings.emptyToNull("")); assertEquals("", Strings.nullToEmpty(null)); // About the only thing we ever used in commons-lang? :) assertTrue(Strings.isNullOrEmpty("")); assertEquals("oioioi", Strings.repeat("oi", 3)); assertEquals("Too short ", Strings.padEnd("Too short", 15, ' }
  • 9. //Some customers Customer bob = new Customer(1, "Bob"); Customer lisa = new Customer(2, "Lisa"); Customer stephen = new Customer(3, "Stephen"); Customer ken = new Customer(null,"Ken");
  • 10. import com.google.common.base.*; @Test public void toStringsAndHashcodes() { Object[] bobAndLisa = new Object[] { bob, lisa }; // Make some hashcode! int hashCode = Objects.hashCode(bob, lisa); assertEquals(Arrays.hashCode(bobAndLisa), hashCode); // Build toString method String string = Objects.toStringHelper(bob) .add("name", bob.getName()) .add("id", bob.getId()).toString(); assertEquals("Customer{name=Bob, id=1}", string); }
  • 11. import com.google.common.base.*; @Test(expected = NullPointerException.class) public void needAnIntegerWhichIsNeverNull() { Integer defaultId = null; Integer kensId = ken.getId() != null ? ken.getId() : defaultId; // this one does not throw! int kensId2 = Objects.firstNonNull(ken.getId(), defaultId); assertEquals(0, kensId2); // But the above does! }
  • 12. import com.google.common.base.*; @Test(expected = IllegalArgumentException.class) public void somePreconditions() { // Pretend this is a constructor: Preconditions.checkNotNull(lisa.getId()); // Will throw NPE Preconditions.checkState(!lisa.isSick()); // Will throw ILE Preconditions.checkArgument(lisa.getAddress() != null, "No description for customer with id %s",lisa.getId()); }
  • 13. import com.google.common.base.*; @Test public void fancierFunctions() { Function<Customer, Boolean> isCustomerWithOddId = new Function<Customer, Boolean>() { public Boolean apply(Customer customer) { return customer.getId().intValue() % 2 != 0; } }; assertTrue(isCustomerWithOddId.apply(bob)); assertFalse(isCustomerWithOddId.apply(lisa)); // Functions are great for higher-order functions, like // project/transform, and fold }
  • 14. import com.google.common.base.*; @Test public void somePredicates() { ImmutableSet<Customer> customers = ImmutableSet.of(bob, lisa, stephen); Predicate<Customer> itsBob = Predicates.equalTo(bob); Predicate<Customer> itsLisa = Predicates.equalTo(lisa); Predicate<Customer> bobOrLisa = Predicates.or(itsBob, itsLisa); // Predicates are great to pass in to higher-order functions // like filter/search Iterable<Customer> filtered = Iterables.filter(customers, bobOrLisa assertEquals(2, ImmutableSet.copyOf(filtered).size()); }
  • 15. import com.google.common.base.*; @Test public void someSuppliers() { //Imagine we have Supploer that produces ingredients IngredientsFactory ingredientsFactory = new IngredientsFactory(); //A function 'bake' - (see next slide) bake(); //Then it's pretty easy to get a Factory that bakes cakes :) Supplier<Cake> cakeFactory = Suppliers.compose(bake(), ingredientsFactory); cakeFactory.get(); cakeFactory.get(); cakeFactory.get(); assertEquals(3, ingredientsFactory.getNumberOfIngredientsUsed()); }
  • 16. import com.google.common.base.*; private Function<Ingredients, Cake> bake() { return new Function<Ingredients, Cake>() { public Cake apply(Ingredients ingredients) { return new Cake(ingredients); } }; }
  • 17. import com.google.common.base.*; @Test public void someThrowables() { try { try{ Integer.parseInt("abc"); } catch(RuntimeException e){ if(e instanceof ClassCastException) throw e; //old-style Throwables.propagateIfInstanceOf(e, NumberFormatException.class); //the same Throwables.propagateIfPossible(e); // Propagates if it is Error or RuntimeException try { Throwables.throwCause(e, true); } catch (Exception e1) { Throwables.propagate(e1); //Wraps if its a checked exception, //or lets it flow if not } } } catch(RuntimeException e){ Throwables.getCausalChain(e); Throwables.getRootCause(e); Throwables.getStackTraceAsString(e); }
  • 18. import com.google.common.base.*; @Test public void someEnums() { assertEquals("UNDER_DOG", CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "underDog")); //Controlling services Service service = new FunkyService(); service.start(); assertEquals(Service.State.RUNNING, service.state()); service.stop(); }
  • 19. import com.google.common.collect.*; @Test public void someSets() { ImmutableSet<Customer> customers1 = ImmutableSet.of(bob, lisa, stephen); ImmutableSet<Customer> customers2 = ImmutableSet.of(stephen, ken); assertEquals(4, Sets.union(customers1, customers2).size()); assertEquals(ImmutableSet.of(stephen), Sets.intersection(customers1, customers2)); }
  • 20. import com.google.common.collect.*; @Test(expected=NullPointerException.class) public void someConstraints() { //instead of new HashSet<Customer>() HashSet<Customer> customers = Sets.newHashSet(); customers.add(null); //this works. But should it? Set<Customer> noMoreNulls = Constraints.constrainedSet(customers, Constraints.notNull()); noMoreNulls.add(null); //boom! }
  • 21. import com.google.common.io.*; @Test public void messAroundWithFile() { File file = new File("woop.txt"); try { Files.touch(file); Files.write("Hey sailor!", file, Charsets.UTF_8); //Breakpoint here.. have a look at the file.. Files.toByteArray(file); Files.newInputStreamSupplier(file); assertEquals("Hey sailor!", Files.readFirstLine(file, Charsets.UTF_8)); assertEquals("Hey sailor!", Files.toString(file, Charsets.UTF_8)); Files.deleteRecursively(file); } catch (IOException e) { Throwables.propagate(e); } }
  • 22. import com.google.common.io.*; @Test public void closingAndFlushing() { InputStream inputStream = System.in; try { inputStream.close();//The old way } catch (IOException e) { Throwables.propagate(e); } Closeables.closeQuietly(inputStream ); //The new way //Or flush: PrintStream outputStream = System.out; Flushables.flushQuietly(outputStream); }
  • 23. import com.google.common.io.*; @Test public void classPathResources() { //This: Resources.getResource("com/tfnico/examples/guava/BaseTest.class"); //instead of this: String location = "com/tfnico/examples/guava/BaseTest.class"; URL resource2 = this.getClass().getClassLoader().getResource(location); Preconditions.checkArgument(resource2!=null, "resource %s not found", location); }
  • 24. import com.google.common.net.InetAddresses; @Test public void iNetAddressIsFixed() { try { /** * Unlike InetAddress.getByName(), * the methods of this class never cause DNS services to be accessed. * For this reason, you should prefer these methods as much as possible * over their JDK equivalents whenever you are expecting to handle only * IP address string literals -- there is no blocking DNS penalty for * a malformed string. */ InetAddresses.forString("0.0.0.0"); //Instead of this... InetAddress.getByName("0.0.0.0"); } catch (UnknownHostException e) { Throwables.propagate(e); } }
  • 25. TODO (For this presentation) • Show off primitives • Show off CharMatcher • Add more collection examples • Add more higher order functions • Do concurrency stuff • Do cooler io stuff • Find patterns of old code that can be replaced
  • 26. When to think Guava? • For loops • Temporary collections • Mutable collections • if( x == null) • In short: method complexity