1. 程式人生 > >Dependency injection on Android: Dagger (Part 1)

Dependency injection on Android: Dagger (Part 1)

On this new series I will explain what dependency injection is, what its main purpose is and how to use it on an Android project by using Dagger, the best know implementation designed with Android in mind.

It will be a follow-up from my previous post about MVP for Android, because I know some of you are quite interested in see them implemented in the same project, and I think they work quite well together.

This first part is going to be only a little theory to settle the basis. It’s important to understand what it is and why it exists, because if not we will think the benefits are not enough for the effort.

What is a dependency?

If we want to inject dependencies, we first need to know what a dependency is. In short, a dependency is a coupling between two modules of our code

(in oriented object languages, two classes), usually because one of them uses the other to do something.

Why dependencies are dangerous?

Dependencies from high to low level are dangerous because we couple both modules in a way that if we need to change one module with another, we necessarily need to modify the code of the coupled module

. That’s really bad if we want to create a testable app, because unit testing requires that when we are testing a module, it is isolated from the rest of modules in our app. To do this, we need to substitute dependencies with mocks. Imagine a code like this:

public class Module1{
   private Module2 module2;

   public Module1(){
      module2 = new Module2();
   }

   public void doSomething(){
      ...
      module2.doSomethingElse();
      ...
   } 
}

How do we test ‘doSomething’ without testing ‘doSomethingElse’? If test fails, what method is the one that is failing? We can’t know. And things get worse if this ‘doSomethingElse’ method saves something in database or performs an API call.

Every ‘new’ we write is a hard dependency we probably need to avoid. And no, writing less modules isn’t a solution, don’t forget single responsibility principle.

How to solve it? Dependency inversion

If we can’t instantiate modules inside another module, we need to provide those modules in another way. Can you imagine how? Exactly, via constructor. That is basically what dependency inversion principle means. You shouldn’t rely on concrete module objects, only on abstractions.

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

Our previous example code would be something like this:

public class Module1{
   private Module2 module2;

   public Module1(Module2 module2){
      this.module2 = module2
   }

   public void doSomething(){
      ...
      module2.doSomethingElse();
      ...
   } 
}

So what’s dependency injection?

You already know! It consists of passing dependencies (inject them) via constructor in order to extract the task of creating modules out from other modules. Objects are instantiated somewhere else and passed as constructor attributes when creating the current object.

But here it comes a new problem. If we can’t create modules inside modules, there must be a place where those modules are instantiated. Besides, if we need to create modules with huge constructors including lots of dependencies, code will become dirty and hard to read, with objects travelling around the inmensity of our app. That’s what a dependency injector solves.

What is a dependency injector?

We can consider it as another module in our app that is in charge of providing instances of the rest of modules and inject their dependencies. That is basically its duty. The creation of modules is localized in a single point in our app, and we have full control over it.

And finally… What is Dagger?

Dagger is a dependency injector designed for low-end devices. Most dependency injectors rely on reflection to create and inject dependencies. Reflection is awesome, but is very time consuming on low-end devices, and specially on old android versions. Dagger, however, uses a pre-compiler that creates all the classes it needs to work. That way, no reflection is needed. Dagger is less powerful than other dependency injectors, but it’s the most efficient.

Is Dagger only for testing?

Of course not! It makes easier to reuse your modules in other apps, or even change them in the same app. Think for example in an app which takes its data from some local files on debug and from an API service on release. That’s perfectly possible by injecting one module or another on each case.

Conclusion

I know this post it’s a bit hard, but I think it’s very important to establish the terms we are going to deal with on next episodes. We already know what dependencies are, what we improve with dependency inversion and how we can implement it by using a dependency injector.

On next episode we will get our hands dirty. so stay tuned!

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

Dependency injection on Android: Dagger (Part 1)

On this new series I will explain what dependency injection is, what its main purpose is and how to use it on an Android project by using Dagger, the

Dagger: dependency injection on Android (Part 2)

If you read first post about dependency injection, you will probably be looking for some real code. There are some beautiful examples about coffee ma

Marginally Interesting: Command Line Interactive Machine Learning on the JVM. Part 1: Why?

Tweet Just to get this out of the way first, no, I’m not going to talk

Experimenting with TensorFlow on Android Part 1

Let us start by installing TensorFlow, I tried a couple methods of installing it and ended up using dockerdocker run -it gcr.io/tensorflow/tensorflow:lates

Android Studio 3.1.4,gradle 4.4解決Error:Unable to resolve dependency for ':@debug/compileClasspath'問題

    最近把Android studio升級到3.1.4,可是新建一個空專案在build的時候都出現問題,本來不是很重視,把不需要的直接注掉即可,但是因為匯入公司的一個專案來編譯,結果還是報了同樣的錯(引入的依賴庫出現了問題),最終在網上找了很多方法,最終解決了,記錄下過程

Our Research on Localization Accuracy of Vehicle Detection Models (Part 1)

Editor’s note: This is the first in a series of three posts outlining the findings of research our in-house computer vision team conducted regarding the ac

Kotlin & Android: A Brass Tacks Experiment, Part 1

Disclaimer: I am a Google employee, but the views expressed in this article are not those of my employer.Kotlin & Android: A Brass Tacks Experiment, Pa

How to use Dagger 2 on Android with Kotlin (KAD 20)

Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later. Although there is some

<Android基礎>(二) Activity Part 1

onclick ddc 靜態 flat 其他應用 art listener 方法 高度 1.活動的基本用法: 1) 手動創建活動、創建加載布局 2) 在AndroidManifest文件中註冊 3) 在活動中添加Button、Toast、Menu 4) 銷毀活動

<Android基礎>(四) UI開發 Part 1

自定義控件 繼續 dial 自定義 button near ati sdi frame 1.常用控件 1)TextView 2)Button 3)EditText 4)ImageView 5)ProgressBar 6)AlertDialog 7)Progre

<Android基礎>(四) Fragment Part 1

ace 開啟 bundle textview contain ima tro aci 簡單的 Fragment 1)Fragment的簡單用法 2)動態添加Fragment 3)在Fragment中模擬返回棧 4)Fragment和活動之間通信 第四章 Fragm

Lesson 2 Building your first web page: Part 1

appear mage ats ref with display sed emp bare In this ‘hands-on’ module we will be building our first web page in no time. W

linux操作系統及命令Part 1

oldboy ont pre 普通 下載 man tro 分隔符 所在 1.關於linux系統的安裝與流程 (1)下載Vmware workstation 與 linux系統(centos版本、redhat版本、Ubuntu版本...)鏡像。 (2)詳細安裝見

Maxmess-Software.On-Site.Survey.2014.1.4 1CD

手機 exida.exSILentia.2014.v2.4.0.25 1CD Maxmess-Software.On-Site.Photo.2010.1.9.1 1CD Maxmess-Software.On-Site.Survey.2014.1.4 1CD PowerSurfacing RE v2.4-4.

Android N 7.1.1】 ActivityManagerService 獲取cpu狀態

nts ota system sna ati andro ood imp use void updateCpuStatsNow() { synchronized (mProcessCpuTracker) { mProcessCpuM

開啟Python取經之路-CLASS-6(Part 1

int code 中標 cnblogs 環境 執行 變量 spa -c 第一個python程序 HELLO WORLD 1 print("hello world") 單行註釋:# 多行註釋:‘‘‘....‘‘‘或者"""....""" 在linux編程中,要在程序中

if else流程判斷-CLASS-11(Part 1

color failed use log user clas elif 輸入 ger if判斷語句 1 if true: 2 print("true") 3 else: 4 print("false") 猜年齡大小 1 # Author:dd 2 ag

如何兩周達到150行Java程序的能力--part 1

指導 編譯 這也 結構 初始化 private rst 能力 知識點 面向對象程序先導課是體系化面向對象課程的重要組成部分,其目標是幫助那些有一定C語言基礎,但對面向對象概念陌生,基本沒碰過Java編程的同學。該課程設計為暑期選修課,因為沒有其他課程,我們設計為現場訓練性質

關於android SDK安裝Failed to fetch URL http://dl-ssl.google.com/android/repository/addons_list-1.xml出錯二

想要 www size lan reload repo 來吧 img details 近日,由於某些原因,大家在使用Android SDK升級的時候。出現了訪問Failed to fetch URL http://dl-ssl.google.co

開源項目Universal Image Loader for Android 說明文檔 (1) 簡單介紹

bst 成功 開源 ica ctu structure 使用 說明 由於  When developing applications for Android, one often facesthe problem of displa