Download Full Dagger by Tutorials Dependency Injection on Android with Dagger Hilt 1st Edition Massimo Carli PDF All Chapters
Download Full Dagger by Tutorials Dependency Injection on Android with Dagger Hilt 1st Edition Massimo Carli PDF All Chapters
Download Full Dagger by Tutorials Dependency Injection on Android with Dagger Hilt 1st Edition Massimo Carli PDF All Chapters
https://ebookfinal.com
https://ebookfinal.com/download/dagger-by-
tutorials-dependency-injection-on-android-with-
dagger-hilt-1st-edition-massimo-carli/
https://ebookfinal.com/download/lover-unleashed-black-dagger-
brotherhood-09-j-r-ward/
ebookfinal.com
https://ebookfinal.com/download/lover-revealed-black-dagger-
brotherhood-04-1st-edition-j-r-ward/
ebookfinal.com
https://ebookfinal.com/download/android-programming-tutorials-3rd-
edition-mark-l-murphy/
ebookfinal.com
https://ebookfinal.com/download/the-thief-black-dagger-
brotherhood-16-first-edition-2nd-printing-edition-j-r-ward/
ebookfinal.com
Core Data by Tutorials iOS 8 and Swift Edition Aaron
Douglas
https://ebookfinal.com/download/core-data-by-tutorials-ios-8-and-
swift-edition-aaron-douglas/
ebookfinal.com
https://ebookfinal.com/download/ios-5-by-tutorials-
volumes-1-and-2-2nd-edition-ray-wenderlich/
ebookfinal.com
https://ebookfinal.com/download/naturoids-on-the-nature-of-the-
artificial-1st-edition-massimo-negrotti/
ebookfinal.com
https://ebookfinal.com/download/the-android-developer-s-cookbook-2nd-
edition-building-applications-with-the-android-sdk-ronan-schwarz/
ebookfinal.com
https://ebookfinal.com/download/dependency-theory-revisited-b-n-ghosh/
ebookfinal.com
Dagger by Tutorials Dependency Injection on Android
with Dagger Hilt 1st Edition Massimo Carli Digital
Instant Download
Author(s): Massimo Carli, the raywenderlich Tutorial Team
ISBN(s): 9781950325177, 1950325172
Edition: 1
File Details: PDF, 20.87 MB
Year: 2020
Language: english
Dagger by Tutorials Dagger by Tutorials
Dagger by Tutorials
By Massimo Carli
Notice of Rights
All rights reserved. No part of this book or corresponding materials (such as text,
images, or source code) may be reproduced or distributed by any means without
prior written permission of the copyright owner.
Notice of Liability
This book and all corresponding materials (such as source code) are provided on an
“as is” basis, without warranty of any kind, express of implied, including but not
limited to the warranties of merchantability, fitness for a particular purpose, and
noninfringement. In no event shall the authors or copyright holders be liable for any
claim, damages or other liability, whether in action of contract, tort or otherwise,
arising from, out of or in connection with the software or the use of other dealing in
the software.
Trademarks
All trademarks and registered trademarks appearing in this book are the property of
their own respective owners.
raywenderlich.com 2
Dagger by Tutorials Dagger by Tutorials
Martyn Haigh is the other tech editor of this book. Martyn started
hacking on Android in 2008 and enjoyed it so much that he went
on to make a career out of it for names like Mozilla and Meet-up.
After over a decade of consulting, he’s currently working as a
senior developer at Facebook. He loves snowboarding, banging
coffee, amazing food and his gorgeous family.
raywenderlich.com 3
Dagger by Tutorials Dagger by Tutorials
raywenderlich.com 4
Dagger by Tutorials
raywenderlich.com 5
Dagger by Tutorials
raywenderlich.com 6
Dagger by Tutorials
Section I: DI Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . 22
Chapter 1: Design Principles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
What dependency means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Types of dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Abstraction reduces dependency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Using your superpower: abstraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Finding the right level of abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Composition over (implementation) inheritance . . . . . . . . . . . . . . . . . . . . . 38
Interface inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Why abstraction is important . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Challenge solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Chapter 2: Meet the Busso App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
The Busso App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Improving the Busso App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
The Rx Module for location . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
raywenderlich.com 7
Dagger by Tutorials
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Chapter 3: Dependency Injection. . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Dependency injection. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Types of injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Busso App dependency management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Challenge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Chapter 4: Dependency Injection & Scopes . . . . . . . . . . . . . . . . 102
Adding ServiceLocator to the Navigator implementation . . . . . . . . . . 103
Going back to injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Chapter 5: Dependency Injection & Testability . . . . . . . . . . . . 120
Model View Presenter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
View & ViewBinder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Presenter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Putting it all together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Key points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
raywenderlich.com 8
Dagger by Tutorials
raywenderlich.com 9
Dagger by Tutorials
raywenderlich.com 10
Dagger by Tutorials
raywenderlich.com 11
Dagger by Tutorials
raywenderlich.com 12
L Book License
• You are allowed to use and/or modify the source code in Dagger by Tutorials in as
many apps as you want, with no attribution required.
• You are allowed to use and/or modify all art, images and designs that are included
in Dagger by Tutorials in as many apps as you want, but must include this
attribution line somewhere inside your app: “Artwork/images/designs: from
Dagger by Tutorials, available at www.raywenderlich.com.
• The source code included in Dagger by Tutorials is for your personal use only. You
are NOT allowed to distribute or sell the source code in Dagger by Tutorials
without prior authorization.
• This book is for your personal use only. You are NOT allowed to sell this book
without prior authorization, or distribute it to friends, coworkers or students; they
would need to purchase their own copies.
All materials provided with this book are provided on an “as is” basis, without
warranty of any kind, express or implied, including but not limited to the warranties
of merchantability, fitness for a particular purpose and noninfringement. In no event
shall the authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from, out of or in
connection with the software or the use or other dealings in the software.
All trademarks and registered trademarks appearing in this guide are the properties
of their respective owners.
raywenderlich.com 13
Before You Begin
This section tells you a few things you need to know before you get started, such as
what you’ll need for hardware and software, where to find the project files for this
book, and more.
raywenderlich.com 14
i What You Need
raywenderlich.com 15
ii Book Source Code &
Forums
• https://github.com/raywenderlich/dag-materials/tree/editions/1.0
Forums
We’ve also set up an official forum for the book at
https://forums.raywenderlich.com/c/books/dagger-by-tutorials/. This is a great place
to ask questions about the book or to submit any errors you may find.
raywenderlich.com 16
iii About the Cover
Dagger by Tutorials
The cassowary is the large bird most closely related to the emu. It’s considered the
most dangerous bird in the world. The dagger-like claw on the inner toe of each foot
is what’s making cassowaries so dangerous. The cassowary can slice open any
predator or potential threat with a single swift kick.
Dagger by Tutorials illustrates the use of the Dagger library to manage dependencies
in the app. It’s not possible to create an application without dependencies. After
reading Dagger by Tutorials, you’ll be armed with Dagger and ready to make your
app testable and maintainable with a single dependency injection library.
raywenderlich.com 17
iv Introduction
You’re likely already doing dependency injection, maybe without even realizing it.
Dependency injection is nowhere near as complex as its name implies.
In this book, you’ll update an existing app named Busso to use dependency injection
with Dagger and Hilt. The Busso app is a simple app that allows you to find bus stops
near you and information about arrival times.
This book will serve you as a central point that holds all the information you need to
dive deep into Dagger and Hilt, to apply it to your personal and production level
projects.
raywenderlich.com 18
Dagger by Tutorials Introduction
If you’re familiar with the fundamentals of dependency injection, you can skip to
“Section II: Introducing Dagger” instead, and continue learning about dependency
injection with Dagger library.
If you’re already using Dagger in your projects, but want to know more about
complex topics, jump over to “Section IV: Advanced Dagger”. You’ll build complex
use cases there on a real-world project, learn about multi-binding and
modularization.
If you’re already proficient with Dagger library, you can skip to “Section V:
Introducing Hilt” and learn about dependency injection with Hilt on Android.
Section I: DI Fundamentals
In this section, you’ll get motivated to use a Dependency Injection (DI) library like
Dagger by learning all about the problem you need to solve: dependency.
You’ll understand what dependencies are and why you need to control them to
create successful apps. You’ll get to know the Busso App, which you’ll work on, and
improve throughout this book. It’s a client-server app where the server is
implemented using Ktor.
You’ll take your next step toward implementing better apps that are easier to test
and modify. You’ll keep the concept of mass of the project in mind. In the process,
you’ll learn more about Scope and see how it relates to dependency.
You’ll also use techniques that would work in a world without frameworks like
Dagger or Hilt to create a fully testable app.
You’ll learn how to deal with constructor, field and method injection with Dagger,
how to simplify the implementation of @Module by using @Binds in cases when
you have abstraction and its implementation, and how to use @Singleton to solve a
very common problem.
raywenderlich.com 19
Dagger by Tutorials Introduction
You’ll learn everything you need to know about Dagger @Modules and you’ll
experiment with using different fundamental annotations like @Binds, @Provides
and BindsOptionalOf as well as useful interfaces like dagger.Lazy and Provider.You’ll
also learn what qualifiers are, how to implement them with @Named and how to use
custom @Qualifiers.
The first migration will not be optimal — there will still be some fundamental
aspects you will improve.
Later, you’ll learn even more about @Components and dependencies. In particular,
you’ll learn why @Singleton is not so different from the other @Scopes, why you
might need a different approach in managing component dependencies, what type of
dependency exist between @Components with @Singleton, @ActivityScope and
@FragmentScope scope, etc.
You’ll implement a simple framework that allows you to integrate new services in
the Busso app in a very simple and declarative way. You’ll learn all you need to know
about multi-binding with Set and Map.
raywenderlich.com 20
Dagger by Tutorials Introduction
Hilt is built on top of the DI library Dagger to benefit from the compile-time
correctness, runtime performance, scalability, and Android Studio support that
Dagger provides.
raywenderlich.com 21
Section I: DI Fundamentals
In this section, understand why you should use a dependency injection (DI) library
like Dagger by learning all about the problem you need to solve: dependency.
You’ll understand what dependencies are and why you need to control them to
create successful apps. You’ll get to know the Busso App, which you’ll work on, and
improve throughout this book. And you’ll take your next step toward implementing
better apps that are easier to test and modify.
raywenderlich.com 22
1 Chapter 1: Design
Principles
By Massimo Carli
In this chapter, you’ll get motivated to use a Dependency Injection (DI) library like
Dagger by learning all about the problem you need to solve: dependency. You’ll
understand what dependencies are and why you need to control them to create
successful apps.
Note: This first chapter describes all the main concepts about object-oriented
programming using a dependency management focus. Go to the next chapter
if you’re already familiar with this topic.
When you thoroughly understand the object-oriented principles of this chapter, the
learning curve of those frameworks, initially steep, becomes flatter and everything
gets easier.
Note: You can find all the code for this chapter in the material section of this
book. It’s a good idea to follow along by adding the code to the starter project
with IntelliJ. You can also check out the complete code in the final project.
The challenge project contains the solutions to the challenges at the end of
the chapter.
raywenderlich.com 23
Dagger by Tutorials Chapter 1: Design Principles
But what does dependency mean? In the previous examples, it means that if the
person you depend on is not available anymore, you need to change your way of life.
If the dependency is economic, you have to reduce your expenses.
Similarly, if the business cuts the budget, you have to change the requirements for
your project or cancel it.
This concept is obvious in the last example because if x changes, y changes as well.
But why are changes important? Because it takes effort to make changes.
The previous examples showed how dependencies can cause changes, and you can
even prove this using physics. Consider the famous principle, Newton’s second law,
shown in Figure 1.1:
This doesn’t mean that change is bad. It just says that if you want to change, you
need to apply effort that’s as big or bigger than the mass m.
Hey, but this is a book about Dagger and Hilt! What does this have to do with your
code?
In the context of coding, dependency is inevitable, and applying changes will always
take some effort. But there are also ways to reduce the mass of your code, reducing
the effort, even for big changes.
This is what you’re going to learn in the following paragraphs. Mastering this skill
will allow you to use tools like Dagger and Hilt effectively and productively.
raywenderlich.com 24
Dagger by Tutorials Chapter 1: Design Principles
Note the “can” because this is something that could, but shouldn’t necessarily,
happen. In the previous examples, A can be you, your project or y. In the same
examples, B can be the person you depend on, the budget of your project or, simply,
x.
In these diagrams, A and B can be different things like objects, classes or even
packages or modules. This is a model that reflects what happens in software
development, where many components interact with many others in different ways.
raywenderlich.com 25
Dagger by Tutorials Chapter 1: Design Principles
On the other hand, it’s not possible to create an app without dependencies. If you
tried, you’d have the opposite problem of a monolithic app: All the code would be in
a single point, making writing code in large teams difficult and testing almost
impossible.
As a developer, one possible solution is to use patterns and practices that allow the
adoption of benign types of dependencies, which is the topic of the following
paragraphs.
Types of dependencies
Figure 1.3 above depicts a generic type of dependency, where the arrow simply
indicates that A depends on B without going into detail. It doesn’t show what A and
B are, or how the dependency looks in code.
Using object-oriented language, you can define relationships more precisely, and you
can do it in different ways for different types of dependencies. In the following
paragraphs you’ll learn about:
1. Implementation Inheritance
2. Composition
3. Aggregation
4. Interface Inheritance
You’ll also learn how abstraction can limit the impact of dependency.
raywenderlich.com 26
Dagger by Tutorials Chapter 1: Design Principles
Implementation inheritance
Implementation Inheritance is the strongest type of dependency. You describe it
using the UML diagram in Figure 1.4 below:
The Student class depends on the Person class because a change of the former has,
as an obvious consequence, a change in the latter — which is the very definition of
dependency.
For example, if you change the Person class by adding eat function, the Student
class now also has the ability to eat.
raywenderlich.com 27
Dagger by Tutorials Chapter 1: Design Principles
A Student differs from a generic Person because they study a particular subject. You
need both Person and Student classes due to two fundamental object-oriented
concepts: The first is that not all people study. The second, more important, concept
is that the fact that some people study may not interest you at all.
You have a Person class so you can generalize people of different types when the
only thing that interests you is that they are people.
For this reason, the statement Student IS-A Person is not the most correct way of
phrasing it. To be more accurate, you’d say: Person is a generalization or
abstraction of Student instead.
This app probably started with Student, then the developers added Person to limit
dependency. As you’ll see in the following paragraphs, they introduced a level of
abstraction to limit the dependency relationship.
Here, you can see that Person describes objects with a name and that they can
think(). A Student IS-A Person and so they can think() but they also study some
topics. All students are persons but not all persons are students.
raywenderlich.com 28
Dagger by Tutorials Chapter 1: Design Principles
fun think() {
println("$name is thinking...")
}
}
A Student has a name, can think and studies a topic. In Figure 1.5 below, you have
its UML representation.
fun main() {
val students = listOf<Student>(
Student("Mickey Mouse"),
Student("Donald Duck"),
Student("Minnie"),
Student("Amelia")
)
printStudent(students)
}
raywenderlich.com 29
Dagger by Tutorials Chapter 1: Design Principles
Mickey Mouse
Donald Duck
Minnie
Amelia
Your program works and everybody is happy… for now. But something is going to
change.
Handling change
Everything looks fine, but the university decided to hire some musicians and create a
band. They now need a program that prints the names of all the musicians in the
band.
You’re an expert now and you know how to model this new item, so you create the
Musician class like this:
Musicians have a name, they think and play a musical instrument. The UML diagram
is now this:
raywenderlich.com 30
Dagger by Tutorials Chapter 1: Design Principles
fun main() {
val musicians = listOf<Musician>(
Musician("Mozart"),
Musician("Andrew Lloyd Webber"),
Musician("Toscanini"),
Musician("Puccini"),
Musician("Verdi")
)
printMusician(musicians)
}
Mozart
Andrew Lloyd Webber
Toscanini
Puccini
Verdi
Everything looks fine and everybody is still happy. A good engineer should smell that
something is not ideal, though, because you copy-pasted most of the code. There’s a
lot of repetition, which violates the Don’t Repeat Yourself (DRY) principle.
Following the same approach, you ended up creating N different classes with N
different methods for printing N different lists of names.
Now, you’ve been asked to do a “simple” task. Instead of just printing the name, the
University asked you to add a Name: prefix. In code, instead of using:
println(it.name)
println("Name: $it.name")
Note: It’s curious how the customer has a different perception of what’s
simple and what isn’t.
raywenderlich.com 31
Dagger by Tutorials Chapter 1: Design Principles
Because of this request, you have to change N printing functions and the related
tests. You need to apply the same change in different places. You might miss some
and misspell others.
The probability of introducing bugs increases with the number of changes you need
to make.
If something bad happens, you need to spend a lot of time fixing the problem. And
even after that, you’re still not sure everything’s fine.
Note: There’s a joke about a consultant who wanted to make their employer
dependent on them. To do that, they only needed to implement the same
feature in many different ways and in many different places. This is no bueno!
To print names, you’re not interested in whether you have Student or Musician. You
don’t care if they study a topic or play an instrument. The only thing that interests
you is that they have a name.
You need a way to be able to see all the entries as if they were the same type,
containing the only thing that interests you: the name.
Here, the need to remove the superfluous leads you to the definition of the following
abstraction, which you call Person:
Abstraction means considering only the aspects that interest you by eliminating
everything superfluous. Abstraction is synonymous with reduction.
raywenderlich.com 32
Dagger by Tutorials Chapter 1: Design Principles
Knowing how to abstract, therefore, means knowing how to eliminate those aspects
that don’t interest you and, therefore, you don’t want to depend upon.
Creating Person means that you’re interested in the fact that a person can think and
you don’t care whether this person can study.
This is an abstract class. It allows you to define the Person type as an abstraction
only, thus preventing you from having to create an instance of it.
Now that you’ve put in the effort, you can reap the benefits of simplifying the
method of displaying names, which becomes:
The advantage lies in the fact that you can print the names of all the objects that can
be considered Person and, therefore, include both Student and Musician.
fun main() {
val persons = listOf(
Student("Topolino"),
Musician("Bach"),
Student("Minnie"),
Musician("Paganini")
)
printNames(persons)
}
raywenderlich.com 33
Dagger by Tutorials Chapter 1: Design Principles
And that’s not all. Returning to the concept of dependency, you can see that adding a
further specialization of Person does not imply any change in the printing function.
That’s because the only thing this depends on is the generalization described by
Person.
With this, you’ve shown how the definition of an abstraction can lead to a reduction
of dependency and, therefore, to changes having a smaller impact on the existing
code.
1. printNames() now depends on the Person abstraction. Even if you add a new
Person specialization, you won’t need to change printNames().
3. Student, Musician and Teacher are some of the realizations of the Person
abstract class. These are concrete classes that you can actually instantiate.
AnyOtherItem is an example of a concrete class you can add without impacting
printNames() in any way.
raywenderlich.com 34
Dagger by Tutorials Chapter 1: Design Principles
But what if you want to print the names for a list of objects for whom the IS-A
relation with Person is not true? What if you want to name cats, vehicles or food? A
cat is not a person, nor is food.
interface Named {
val name: String
}
Now, each person implements the Named interface. So do the Student, Musician,
Teacher and other realizations of the Person abstract class.
The good news is that now you can create Cat like this:
raywenderlich.com 35
Dagger by Tutorials Chapter 1: Design Principles
fun main() {
val persons = listOf(
Student("Topolino"),
Musician("Bach"),
Student("Minnie"),
Musician("Paganini"),
Cat("Silvestro")
)
printNames(persons)
}
Topolino
Bach
Minnie
Paganini
Silvestro
In the context of printing names, all the objects are exactly the same because they all
provide a name through a name property defined by the Named interface they
implement.
This is the first example of dependency on what a specific object DOES and not on
what the same component IS. You’ll learn about this in detail in the following
paragraphs.
raywenderlich.com 36
Dagger by Tutorials Chapter 1: Design Principles
2. Person implements the Named interface and you can now use each of its
realizations in printNames().
3. Cat implements the Named interface, printNames() can use it and it has nothing
to do with the Person class.
raywenderlich.com 37
Dagger by Tutorials Chapter 1: Design Principles
Now you can say that Cat as well as Student, Musician, Teacher and any other
realization of Person IS-A Named and printNames() can use them all.
This means that if you want to implement a new feature, you should add the new
thing without changing the existing code.
In the previous example, to add a new object compatible with printNames(), you
just need to make a new class that implements the Named interface. None of the
existing code needs to be changed.
This change is actually a big thing, because it’s your first example of dependency on
what an object DOES and not on what the same object IS.
In the printNames() example, this further reduced the dependency on the Person
abstraction.
This is a very important principle you should always consider in your app: Program
to an interface, not an implementation.
This principle is also true in real life. If you need a plumber, you don’t usually care
who that plumber is. What’s important is what they do. You want to hire the plumber
who can fix the pipes in your house.
Because of this, you can change who you use as your plumber if you have to. If you
need a specific plumber because of who they are, you need to consider a course of
action if they aren’t available anymore.
raywenderlich.com 38
Dagger by Tutorials Chapter 1: Design Principles
Composition
A classic example of dependency on what an object does is persistence
management.
Suppose you have a server that receives requests from clients, collects information
then stores it within a repository.
In this case, it would be completely wrong to say the Repository IS-A Server or the
Server IS-A Repository.
So if you were to represent the relationship between Server and Repository, you
could say that the former uses the latter, as the UML diagram in Figure 1.9 shows:
How do different entities communicate? In this case, Server must have a reference
to Repository and then invoke one or more methods on it. Here, you can suppose it
invokes save(Data) with a parameter of type Data.
You can represent the previous description with the following code:
class Repository {
fun save(data: Data) {
// Save data
}
}
class Server {
private val repository = Repository()
raywenderlich.com 39
Dagger by Tutorials Chapter 1: Design Principles
Everything looks perfect, but a problem arises as soon as you represent the previous
relationship through the UML diagram in Figure 1.10:
You can say that Server composes Repository. As you can see in the previous code,
Server has a private local variable of Repository. It initializes with an instance of
the Repository class itself.
• Repository and Server have the same lifecycle. The Repository instance is
created at the same time as the Server instance. Repository dies when Server
does.
raywenderlich.com 40
Random documents with unrelated
content Scribd suggests to you:
joyeux compagnon plein de franchise et d’entrain, d’un de ces
viveurs incorrigibles qui s’écrient encore à quarante ans : Il faut bien
que jeunesse se passe !
En général, les chevaliers d’industrie se connaissent d’instinct,
sinon de réputation. D’ailleurs, Cinqpoints et Blewitt, bien que volant
chacun dans une sphère différente, s’étaient rencontrés aux courses
et dans quelques réunions de joueurs. Jusqu’à ce jour, mon noble
maître, qui savait ce qu’il se devait à lui-même, n’avait point voulu se
compromettre en fréquentant un escroc de bas étage ; mais, peu de
temps après l’installation de Dakins, il commença à se montrer fort
affable envers son voisin. Le motif de ce changement de conduite
saute aux yeux : ayant deviné les intentions de Blewitt à l’égard du
nouveau locataire, Cinqpoints voulait avoir sa part du butin.
— John, quel est donc ce voisin qui a une passion si
malheureuse pour le flageolet ? me demanda-t-il un matin.
— Il se nomme Dakins, monsieur : c’est un jeune homme fort
riche et un ami intime de M. Blewitt.
Cinqpoints ne poussa pas plus loin cet interrogatoire ; il en savait
déjà assez. Un sourire diabolique dérida son visage, où je pus lire le
raisonnement que voici :
No I
(Note du traducteur.)
No II
Situation financière de l’Honorable Percy Cinqpoints, au mois d’août
18…
Fr. C.
Compte à notre débit au club de Crockford 68,775 »
Billets et lettres de change en circulation (nous ne les 124,075
en retirions presque jamais) »
Notes de vingt et un tailleurs 26,172 90
Item de trois marchands de chevaux 10,050 »
Item de deux carrossiers 7,836 75
Dettes oubliées à Cambridge 34,832 80
Mémoires de divers fournisseurs 12,675 35
Total 298,417
80
I. O. U.
Quatre mille sept cents livres sterling.
Thomas Dakins.
Vendredi, 13 janvier.
Cela voulait dire : « Je vous dois cent dix-sept mille cinq cents
francs. »
Ce chiffon sans prétention était aussi valable qu’un billet de
banque, car Blewitt avait eu soin de prévenir Dakins que Cinqpoints,
fort chatouilleux sur le point d’honneur, avait tué en duel deux
joueurs assez malhonnêtes pour refuser de payer une dette de jeu.
Je trouvai un autre papier du même genre signé Richard Blewitt,
pour une somme de dix mille francs ; mais je savais que celui-là ne
signifiait rien.
. . . . . . . . . . . . . . . . . . . .
Le lendemain matin, l’Honorable Percy Cinqpoints se trouva
debout dès neuf heures, aussi sobre qu’un juge. Il s’habilla et se
rendit chez Dakins. Environ une heure après, il demanda son
cabriolet, dans lequel il monta avec sa dupe.
Pauvre Dakins ! Les yeux rouges, la poitrine gonflée de sanglots
comprimés, il se laissa tomber à côté de mon maître sans prononcer
une parole, avec ce frisson fiévreux que donne une nuit d’insomnie
et de remords.
Sa fortune consistait en rentes sur l’État. Ce jour-là, il vendit tout,
à l’exception d’un capital d’une dizaine de mille francs.
. . . . . . . . . . . . . . . . . . . .
Vers deux heures, Cinqpoints était de retour. Son ami Blewitt se
présenta pour la troisième fois.
— Votre maître est rentré ? demanda-t-il.
Je répondis affirmativement.
J’annonçai sa visite ; puis, dès que j’eus refermé la porte du
salon, je regardai par le trou de la serrure, et j’ouvris l’oreille.
— Eh bien, dit Blewitt, nous avons fait un assez joli coup de filet,
mon cher Cinqpoints… Il paraît que vous avez déjà réglé avec
Dakins ?
— En effet, monsieur.
— Cent dix-sept mille cinq cents francs, je crois ?
— Mais oui… A peu près.
— Cela fait, pour ma part… voyons un peu… oui, cela fait
cinquante trois mille sept cent cinquante francs, que vous avez à me
remettre, mon cher.
— Vraiment, monsieur Blewitt, je ne vous comprends pas du tout.
— Vous ne me comprenez pas ! s’écria l’autre d’un ton de voix
impossible à décrire. N’est-il pas convenu que nous devons partager
les bénéfices ? Ne vous ai-je pas prêté de quoi payer vos pertes des
deux premières soirées ? Ne m’avez-vous pas donné votre parole
d’honneur que vous me remettriez la moitié de ce que je vous
aiderais à gagner ?
— Tout cela est parfaitement exact.
— Alors, que diable avez-vous à objecter à ma réclamation ?
— Rien… si ce n’est que je n’ai jamais eu la moindre intention de
tenir ma promesse… Ah çà, vous êtes-vous vraiment imaginé que
j’allais travailler pour vous ? Avez-vous été assez idiot pour vous
figurer que j’avais donné à dîner à ce nigaud, afin de mettre de
l’argent dans votre poche ?… Ce serait trop drôle, et j’ai meilleure
opinion de vous… Allons, monsieur, cessons cette plaisanterie. Vous
savez où est la porte… Mais attendez un instant. Je serai généreux ;
je vous donnerai dix mille francs pour la part que vous réclamez
dans cette affaire… Tenez, voici votre propre billet pour cette
somme ; je vous le rends, à condition que vous oublierez avoir
jamais connu l’Honorable Percy Cinqpoints.
Blewitt gronda, cria, gémit, pria, menaça, frappa du pied. Tantôt il
jurait et grinçait des dents ; tantôt il suppliait son cher M. Cinqpoints
d’avoir pitié de lui. Finalement, il se mit à pleurnicher comme un
enfant.
Mon maître, impatienté, ouvrit la porte du salon, où je manquai
de tomber la tête la première.
— Reconduisez monsieur, me dit Cinqpoints en regardant Blewitt
dans le blanc des yeux.
Ce dernier quitta le canapé sur lequel il s’était jeté avec un geste
de désespoir, et sortit, faisant une mine aussi piteuse qu’un chien
qu’on menace du fouet. Quelques années plus tard, il eut
l’imprudence de commettre un faux, et fut transporté à Botany-Bay.
Quant à Dakins, Dieu sait ce qu’il est devenu ; moi, je l’ignore.
. . . . . . . . . . . . . . . . . . . .
— John, dit mon maître, lorsque j’eus reconduit le visiteur, John,
je vais à Paris. Vous pouvez m’accompagner si cela vous convient.
II
IMPRESSIONS DE VOYAGE
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookfinal.com