Question

I've been watching Jake's slides about Dagger. At the page #29, he said 'Separate "do" from the "how"'. What specifically does that mean? And what are the benefits of it?

https://speakerdeck.com/jakewharton/android-testing?slide=29

Was it helpful?

Solution

If I had to expand the sentence it would be: "The code that needs to 'do' an action should not need to know 'how' that action is fulfilled."

This is a fundamental principle that can be lumped under a lot of different phrases but can most concretely be explained as interfaces and implementations in Java.

When you use a Set in Java you are concerned with the behavior: each element only appears once. Java provides multiple implementations of a Set. Each implementation fulfills the contract of the interface using different techniques: hash buckets, trees, or bits.

Code that interacts with the Set only cares about the behavior, not how it is achieved.

The same semantics can be applied to many different things in your application. My favorite example is something that posts tweets.

interface Tweeter {
  void postTweet(String message);
}

If I'm a class that wants to post tweets, all I care about it the ability to send a tweet.

public MyClass(Tweeter tweeter) {
  this.tweeter = tweeter;
}

@Override
public void run() {
  tweeter.postTweet("I'm a Runnable that's being run!");
}

How does the tweet get sent? From the perspective of MyClass, who cares!

In my real application I will of course use a TwitterTweeter (either directly when instantiating MyClass or via dependency injection). However, I now have the ability to pass in a MockTweeter of my own implementation to write a test that asserts that when a MyClass is run() it posts a tweet.

Things like this might seem obvious, but it's not a rarity to see code that (for this example) needs to posts a tweet and knows exactly how to do so.

Before I leave, two important points:

  • Interfaces and implementations are not the only way to accomplish this, they're just a very effective means of doing so.
  • Abstraction in this form is icing on a cake. A cake without icing sucks. But a cake with 5inch-thick icing also sucks. Apply it where it's needed and logical.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top