Dagger 2 Injeção de dependências no mundo Android

Post on 20-Jan-2017

59 views 1 download

Transcript of Dagger 2 Injeção de dependências no mundo Android

INJEÇÃO DE DEPENDÊNCIAS NO MUNDO ANDROID

CLÊRTON LEAL

QUEM SOU EU

▸ Clêrton Leal

▸ Nascido e criado na cidade de Fortaleza

▸ Trabalhando como consultor para a Avenue Code de Belo Horizonte

▸ Morando em BH a pouco mais de 5 meses =)

DAGGER 2

TÓPICOS DE HOJE

▸ Histórico sobre Injeção de Dependências no mundo Android e porque devemos usar o Dagger 2 para isso.

▸ Injeção de Dependências como um padrão de projetos e quais suas vantagens.

▸ Como aplicar Dagger 2 em seus projetos Android.

SENTA QUE LÁ VEM HISTÓRIA

INJEÇÃO DE DEPENDÊNCIAS NO ANDROID

▸ RoboGuice

▸ Dagger

▸ Dagger 2

ROBOGUICE

É UMA EXTENSÃO DO PROJETO GUICE, CRIADO PELO GOOGLE EM 2006 POR BOB LEE E JESSE WILSON.

LANÇADO EM 2010 E FOI UMA ENORME EVOLUÇÃO NA CRIAÇÃO DE APPS ANDROID.

PONTOS POSITIVOS

▸ Módulos facilmente testáveis

▸ Códigos de fácil manutenção

▸ Nada de XMLs de configuração

▸ Muitas facilidades para o desenvolvimento Android

O GUICE É 100% BASEADO EM REFLECTION. =/

PONTOS NEGATIVOS

▸ Problemas de injeção aconteciam apenas em Runtime.

▸ Logs de erros extremamente ruins.

▸ Debug difícil e com uma stack confusa.

▸ Muito lento para inicialização e injeção em geral.

TODOS OS PROBLEMAS DO GUICE OCORREM EM TEMPO DE EXECUÇÃO

UMA FORMA MAIS INTELIGENTE SERIA TRATAR AS INJEÇÃO EM TEMPO DE COMPILAÇÃO

DAGGER

EM 2011 A SQUARE CONTRATA BOB LEE E JESSE WILSON.

EM 2012 É LANÇADO O DAGGER.

PONTOS POSITIVOS

▸ O Dagger tem como lema: “Falhe o mais cedo possível”.

▸ Análise de todas as dependências e injeções em tempo de compilação.

▸ Eliminado uso de Reflection na injeção de métodos, campos e processamento de annotations.

▸ Escalabilidade. Pode ser usado sem problemas em grandes projetos.

▸ Detecção de dependências cíclicas em tempo de compilação.

AINDA USA REFLECTION PARA CARREGAR AS CLASSES GERADAS EM TEMPO DE COMPILAÇÃO

DAGGER 2

EM 2013 A GOOGLE PUBLICOU UMA ESPECIFICAÇÃO DE UMA VERSÃO MELHORADA DO DAGGER.

A COMUNIDADE DO DAGGER SE DIVIDIU ENTRE SQUARE E GOOGLE. ASSIM O PROJETO FOI FORKED.

EM 2014 O DAGGER 2 FOI LANÇADO COMO UM PROJETO DO GOOGLE PARA INJEÇÃO DE DEPENDÊNCIA DE ALTA PERFORMANCE.

DAGGER 2

▸ Proposto, desenvolvido e mantido pelo Google.

▸ Eliminou 100% do uso de reflection no projeto.

▸ Transferiu toda a analise de código restante de Runtime para compilation time.

▸ Fácil de debugar e com uma stack de execução limpa.

▸ Stack trace limpo e de fácil análise.

NEGATIVOS

DAGGER 2

▸ Menos flexível que outros DI frameworks.

INJEÇÃO DE DEPENDÊNCIAS

PRIMEIRAMENTE TEMOS QUE ENTENDER QUE INJEÇÃO DE É UMA PADRÃO DE PROJETOS E NÃO É SOBRE FRAMEWORKS DA MODA.

TODO PROJETO TEM DEPENDÊNCIAS.

public class TwitterApi { private final OkClient okClient; private final TwitterAuth twitterAuth; public TwitterApi() { this.okClient = new OkClient(); this.twitterAuth = new TwitterAuth(okClient); } public void postTweet(String tweet) { /*Posting tweet*/ } }

public void doTweet() { TwitterApi twitterApi = new TwitterApi(); twitterApi.postTweet("Dagger é amor. <3"); }

GRAFICO DE DEPENDÊNCIAS

Twitter API

Twitter Auth

OkClient

public class TwitterApi { private final OkClient okClient; private final TwitterAuth twitterAuth; public TwitterApi() { this.okClient = new OkClient(); this.twitterAuth = new TwitterAuth(okClient); } public void postTweet(String tweet) { /*Posting tweet*/ } }

public class TwitterApi { private final OkClient okClient; private final TwitterAuth twitterAuth; public TwitterApi(OkClient okClient, TwitterAuth twitterAuth) { this.okClient = okClient; this.twitterAuth = twitterAuth; } public void postTweet(String tweet) { /*Posting tweet*/ } }

public void doTweet() { TwitterApi twitterApi = new TwitterApi(); twitterApi.postTweet("Dagger é amor. <3"); }

public void doTweet() { OkClient okClient = new OkClient(); TwitterAuth twitterAuth = new TwitterAuth(okClient); TwitterApi twitterApi = new TwitterApi(okClient, twitterAuth); twitterApi.postTweet("Dagger é amor. <3"); }

TWITTER API HTTP CLIENT

TWITTER AUTH

COMPLEXIDADE É UM PROBLEMA.

MAS O QUE EU GANHO COM ESSA COMPLEXIDADE A MAIS NO MEU CÓDIGO?

TESTABILIDADE!!!

public class TwitterApi { private final OkClient okClient; private final TwitterAuth twitterAuth; public TwitterApi() { this.okClient = new OkClient(); this.twitterAuth = new TwitterAuth(okClient); } public void postTweet(String tweet) { /*Posting tweet*/ } }

public class TwitterApi { private final OkClient okClient; private final TwitterAuth twitterAuth; public TwitterApi(OkClient okClient, TwitterAuth twitterAuth) { this.okClient = okClient; this.twitterAuth = twitterAuth; } public void postTweet(String tweet) { /*Posting tweet*/ } }

DAGGER NÃO TRÁS INJEÇÃO DE DEPENDÊNCIAS PARA O SEU PROJETO.

DAGGER TRÁS A SIMPLIFICAÇÃO DO USO DE INJEÇÃO DE DEPENDÊNCIAS.

public void doTweet() { OkClient okClient = new OkClient(); TwitterAuth twitterAuth = new TwitterAuth(okClient); TwitterApi twitterApi = new TwitterApi(okClient, twitterAuth); twitterApi.postTweet("Dagger é amor. <3"); }

@InjectTwitterApi twitterApi; public void doTweet() { twitterApi.postTweet("Dagger é amor. <3"); }

TWITTER API HTTP CLIENT

TWITTER AUTH

MAIN APP

DAGGER 2 API

API

▸ @Module: Mecanismo para prover dependências a serem injetadas.

▸ @Inject: Mecanismo que requer a injeção de uma dependência.

▸ @Component: Elo entre os modules e os injetáveis.

VAMOS AO CÓDIGO

OBRIGADO

PERGUNTAS?

‣ CLERTONLEAL@GMAIL.COM ‣ @CLERTONLEAL ‣ HTTPS://GITHUB.COM/CLERTONLEAL/DAGGER-TALK