Você já viu aquele projeto Java com um pacote utils, commons, helpers e por aí vai? Vamos mostrar como aumentar sua produtividade e deixar a vida mais leve usando os componentes da biblioteca Guava. https://plus.google.com/u/0/events/ck9ni6b2g1spetp25ohuu1sf6cc
3. Problema: ler um arquivo
try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}
4. Software baseado em componentes
● Don’t repeat youself!
● Faça você mesmo ou pegue pronto.
● Interface bem definida e sem estado.
● Pode ser substituído por outro
componentes
5. Guava
● https://github.com/google/guava
● Java 1.6 ou maior
● Usadas em projetos Java do Google
● collections, caching, primitives support, concurrency libraries, common
annotations, string processing, I/O ...
8. Lidando com valores nulos
Integer a=5;
Integer b=null;
//algumas operações
Optional<Integer> possible=Optional.fromNullable(a);
System.out.println(possible.isPresent());//tem algo não nulo?
System.out.println(possible.or(10));//se for nulo, retorna 10 por padrão
System.out.println(MoreObjects.firstNonNull(a, b));//seleciona entre dois
valores
String nome=new String();
System.out.println(Strings.isNullOrEmpty(nome));
9. Pré condições
import static com.google.common.base.Preconditions.checkElementIndex;
Integer[]arr=new Integer[5];
//algum código
int index=5;
checkElementIndex(index, arr.length, "index");
/*
Exception in thread "main" java.lang.IndexOutOfBoundsException: index (5) must be
less than size (5)
at com.google.common.base.Preconditions.checkElementIndex(Preconditions.java:
310)
at br.gdg.fsa.Main.main(Main.java:43)
*/
10. Pré condições
import static com.google.common.base.Preconditions.checkNotNull;
Integer a=null;
checkNull(a);
/*
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:212)
at br.gdg.fsa.Main.main(Main.java:45)
*/
11. Pré condições
import static com.google.common.base.Preconditions.checkArgument;
int i=-1;
checkArgument(index >= 0, "Argument was %s but expected nonnegative", index);
/*
Exception in thread "main" java.lang.IllegalArgumentException: Argument was -1 but
expected nonnegative
at com.google.common.base.Preconditions.checkArgument(Preconditions.java:146)
at br.gdg.fsa.Main.main(Main.java:46)
*/
12. Comparação de objetos
class Person implements Comparable<Person> {
public String lastName;
public String firstName;
public int zipCode;
public int compareTo(Person other) {
int cmp = lastName.compareTo(other.lastName);
if (cmp != 0) {
return cmp;
}
cmp = firstName.compareTo(other.firstName);
if (cmp != 0) {
return cmp;
}
return Integer.compare(zipCode, other.zipCode);
}
}
13. Comparação de objetos com Guava
class Person implements Comparable<Person> {
public String lastName;
public String firstName;
public int zipCode;
public int compareTo(Person that) {
return ComparisonChain.start()
.compare(this.lastName, that.lastName)
.compare(this.firstName, that.firstName)
.compare(this.zipCode, that.zipCode)
.result();
}
}