Getting stabbed by Dagger on Android


Did you read the title?It saysI got stabbed, by Dagger, on Android. The non-technical reader would assume something serious occurred followed by hospitalization. Those who know me are already wondering what the dependency injection framework I’ve come to love and how it could have any pointy edges. While I actually have physically been stabbed in the not too distant past (long embarrassing story and I don’t wanna get into it) I can assure you today’s situation does not involve anything breaking my skin. Hi, I’m Cliff. You’re here because you’ve been stabbed by Dagger. You may not need bandages or medical care but it hurts kinda bad. I’m here because I was bleeding a little while ago and I want to share my experience.

The catalyst for today’s post revolves around the suspicious error messages I was seeing from Dagger from time to time. I sort of know how to use it pretty well but when I’m in a rush I tend to make subtle mistakes that lead to even more subtle but hard to decipher error messages. These errors don’t always steer me to the source of the problem, rather they leave me with a feeling of, “that doesn’t make sense!” As Dr. House says, “When something doesn’t make sense, one of your assumptions is flawed.” (I love House!) All rambling aside, let’s get to the important part. Below I’ll list a few error messages along with what they might be trying to tell you. Remember, the best way to debug a program is to force an error early on and get used to the random messages it generates. I’m saving you a bit of time by doing some of this rework for you in Dagger.

Error:
java.lang.IllegalArgumentException: No inject registered for members/com.your.package.YourInjectedClass. You must explicitly add it to the 'injects' option in one of your modules.

at dagger.ObjectGraph$DaggerObjectGraph.getInjectableTypeBinding(ObjectGraph.java:302)
at dagger.ObjectGraph$DaggerObjectGraph.inject(ObjectGraph.java:279)
at com.your.package.YourInjectedClass.init(YourInjectedClass:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)

Cause:
You may have tried to inject a class that is not declared in the Module you’re using to do injection. For eg., if you call ObjectGraph.create(MyModule.class).inject(this); and this object does not appear in MyModule then you probably should add it to the @Module annotation like so:
@Module(library = true, injects = YourInjectedClass.class)

Error:
Compilation completed with 1 error and 0 warnings in 2s 455ms
/Users/you/src/YourProject/src/test/java/your/package/YourInjectedClass.java
Error:Error:line (37)java: your.package.someInjectedDependency could not be bound with key your.package.someInjectedDependency required by YourInjectedClass for YourInjectedClassModule

Cause:
You may be missing a providing method in our module or more likely you’ve forgotten the @Provides annotation. If YourInjectedClass decades an injected variable of type your.package.someInjectedDependency, check that your.package.someInjectedDependency is returned from some providing method and that the method includes the @Provides annotation like so:

@Provides
public someInjectedDependency providesSomeInjectedDependency() {
return new someInjectedDependency();
}

Error:
java.lang.UnsupportedOperationException: No no-args constructor on at com.your.package.YourInjectedClass$YourInjectedClassModule$$ModuleAdapter

at dagger.internal.ModuleAdapter.newModule(ModuleAdapter.java:58)
at dagger.internal.Modules.loadModules(Modules.java:41)
at dagger.ObjectGraph$DaggerObjectGraph.makeGraph(ObjectGraph.java:174)
at dagger.ObjectGraph$DaggerObjectGraph.access$000(ObjectGraph.java:138)
at dagger.ObjectGraph.create(ObjectGraph.java:129)
at com.your.package.YourInjectedClass.setUp(YourInjectedClass.java:22)

Cause:
I got this error by doing something really strange/non-standard. It just means that it cannot instantiate your Module class. In my case I had defined my module class in the same file as the class that was asking for injection but outside the class definition. (This is outside the last curly brace enclosing the contents of the class’ methods.) I then moved inside the class definition but forgot to make it a static. This caused Dagger to not be able invoke the constructor because that only works for static inner classes… if none of this makes any sense to you don’t think about. Just know that the error above means that you should check the visibility of your module class (eg. is it a private class or a public class? Does it have a public no-arg constructor? Is it in the classpath?)

There’s other weird errors I’m trying to get used to and I’ll either post here or write a new article as I discover them.

Year 1 at the worlds oldest company, GE


Earlier I tried to log into the task board at work. Y’know that board thingy that has the cards that represent the work you could’a should’a would’a done but you’re still in the middle of that other task thing that is no where on the board. Anyway, as soon as I opened the page I was greeted by an awful terrible thing… something so rotten it will keep you up in cold sweats… you’ll never look at a computer screen the same way after seeing this thing… It was the password reset screen! Hi, I’m Cliff. You’re here because your password just expired and I’m here to remind you not to use the same one over with just two characters transposed.

It’s that time of year when stock options start to vest and you begin to lose access to critical systems while mis-keying your new uncommitted to memory nonsense word that most include at least two digits, one capital letter, begin and end with a letter, and rhyme with “silver”. You must also compliment this nonsense word with random answers to common questions like, “other than pink, fuscha, green, red and yellow what is your favorite color?” and, “what is your first car which everybody remembers you driving from high school because you crashed it into a tree?” These hard to guess combinations will guarantee that everyone but you can access your sensitive accounts as you struggle to remember the proper casing for the name of the city you grew up in. (was it “Mt Holly” or “Mount Holly” or did you get totally lazy and key in “mount holly”?) A few dozen call to IT and a couple hours later and you’re right back to trying to recall your first pet’s name while setting a new gobble-gook phrase that you’re sure to remember since this time it reminds you of the lady at the grocery store that hooks you up with extra paper bags without charge the $.10 fee.

So what have I done this past year? I’ve managed to write an Android app which my team is hoping to finish and publish as part of our mobile platform. I’ve picked up the Kotlin language. (…and put it back down once I realized how over-committed my schedule became.) I learned nodeJS/TypeScript/Electron by fire. I helped to organize a mobile workshop. I helped a developer’s hangout. I’ve done several product demos. I’ve basically been Mr. Mobile Phone-pants around the office. I would say that I’ proud of my accomplishments but I don’t really feel like I’ve accomplished anything.

Overall I really love working at this company… it’s not something I thought I’d every get used to. I mean, let’s be honest… this place is not known for anything fancy like social networking or streaming video, or fancy cartoony game characters or anything. AS a matter of fact, the first thing that comes to mind when hearing or thinking of the GE brand is some sort of chore I used to try to avoid when I was younger. That said, I am blown away with how much fun I’ve had over the last 12 months. Here’s hoping the next twelve are just as exciting!

Hello World Part C


It’s my 10 year blog-o-versary and I’m fashionably late with an update. Here go my first post way back in 2006 before I knew what I was doing. Not much has changed since 2006. Hi, I’m still Cliff. I’m still the lucky husband of one spectacular woman, though if I told you m story you probably wouldn’t believe me. My site still only consists of 2 regular visitors. Over the last 10 years I’ve consistently posted articles that chronicle my discoveries and experience with various tech. My jokes have slightly improved from corny to I can just skip passed the stoopid parts. I’ve worked at some fascinating companies on some high profile projects over the years, mostly mobile. and peanut butter has been a regular part of my daily balanced meals. I always thought I would be blog famous by now… someone like Joel Spolsky. I’m not mad though… I got John Blazed articles and all… most people just don’t understand. Still I’m cool with being humble. I don’t need too many people reading through my typos, grammatical errors, and terribly embarrassing attempts to be funny. You know how when you write a joke that you think is so funny but then come back and read it years later and feel like, “why did I think that was my Kevin Hart moment?” There’s a few posts here that read like that. You may have read one or two. If so, don’t clown… just keep it moving. I ain’t trying to change the embarrassing stuff I posted way back. It’s been here far too long and is now part of my makeup. (It’s not like I actually wear makeup, it’s just that the dumb stuff… along with the somewhat presentable stuff is sort of what makes me up. If you were gonna tease me about wearing makeup then you’re part of what’s wrong with society because I should feel free to wear makeup if I please.. not that I want to… but if I did… where was I??? Oh, yeah, outside the parenthesis…)

So over the years I’ve talked about how to suck at programming, Linux hacks, Siri, J2ME & Blackberry, video games, and of course unit testing. By far one of my most favorite gems is the TDD example I wrote which counts how many emcees must get dissed. I had a bit of fun with that post though I think it has errors that I should probably correct. There were a few other classics as well like the post where I learned how to REALLY use SSH or the one where I figured out how to use ALSA on Linux to play pleasant cues/blips from Apple encoded files pulled of of my Macbook. I’ve also posted some low level discussion on how NSViews work on OS X even though I never wrote an OS X app at all in my entire life. I get a thrill out of posting random things I’ve learned/discovered over the years.

In all I have to say I’m both surprised and thrilled with how long I’ve kept this blog up. There have been some dry spells over the years but I eventually find time to post stuff as I learn it. Here’s celebrating my 10 years of foolish but technical gibberish!

IntelliJ Idea loses my test resources!


Are your tests failing because the resource files cannot be found? All of the sudden I hit this problem where a few of my tests started to fail for no reason. They were unable to locate the test resources I was using and at first this looked like an ancient issue. The old issue I had been familiar with before involved a clumsy work-around where you would hack your Gradle build to copy the test resources folder into the test classes folder. This still works but is not necessary. While the bug still exists the current work around is to click the Gradle sync button to resynchronize your project with the Gradle build. (I discovered the fix here.) This seems to work for me for now.

Test First, ask questions later…


I’ve been doing this test first thing for a while and now I’m in a position where I’m teaching others how to properly design code with this practice. I’m using it in my current project and I’ve also been hanging out in the code newbie community answering questions and confusing others. I usually respond to arbitrary questions with something hinting to the need to write test code. Here’s some typical exchanges I have throughout my week:

Them: “I can’t find the source to this null pointer exception…”

Me: “Can you isolate the issue with a failing test?”

Them: “My REST call is returning 403”

Me: “You know you can use Selenium in these scenarios to…”

Them: “I think this method is going to be slow.”

Me: “Do you have a failing performance test that indicates we should optimize here?”

Them: “You have a few dollars? I forgot to pack a lunch…”

Me: “I usually have a checklist I refer to prior to leaving the house for things like my employee badge, my lunch, etc. I highlight each item with a green bar prior to jumping in the car…”

My Kids: “Daddy, I don’t feel well. Can I stay home today?”

Me: “I thought I told you about going outside without proper test coverage! You probably got a regression of your symptoms from last week!”

Needless to say it’s a very important topic and always forefront on my mind. I lead with a test case. One person in particular drew an interest and asked a basic question about unit testing. Not paying attention to who it was I sorta went all out in my explanation without really understanding the level of expertise. Usually I get the typical response of, “You’re a bit extreme, bro! Calm down!” She was not intimidated at all. Instead, she was rather appreciative, which I’m thankful for because I really went full throttle in my response. I don’t really have an off switch when I get on that topic so I ended up writing roughly 2 pages of text before I came up for air. The question was something along the lines of, “how do I test my method that calculates my layout dimensions based on screen size?” My brain jumped immediately to “Test First!” without asking any pause to ask questions about the project, deadline, or backstory. In short, here’s what I attacked with. (Yes it was an unsolicited attack on an innocent bystander but I have no filter when it comes to these things):

See there are 3 levels of testing as I like to see it.
* Functional testing
* Integration testing
* Unit testing

[8:13]
Each level sits on top of the levels beneath it and has certain characteristics.

[8:36 AM]
Functional testing is the type testing where you test the app in its entirety end to end for broad functionality.

[8:37]
This involves testing the app in its deployed environment (device or emulator) and may or may not be automated by tools.

[8:38]
Integration testing is where you test two or more components of your app in isolation. In these types of tests you are exercising the integration points of particular components. I.e. does objectA integrate and play nicely with objectB?

[8:39]
A component may be represented by something as coarse grained as a library or module, or something as fine grained as an object or a method.

[8:40]
Again, you are primarily testing to make sure the pieces work together.

[8:41]
Unit testing the the final level of testing. It is here where you test specific objects and/or methods in isolation.

[8:41]
Why am I telling you all of this?

[8:41]
(I’m so glad you asked!)

[8:42]
The thing is that each level should focus primarily on a specific type of testing.

[8:43]
With functional tests you test broad functionality. These should be very coarse grain tests and not too specific. These tests are a way of asking, “does my app function as a whole?”

[8:44]
They run on device and as a result they are slow and cumbersome. These are the tests that normally make use of Espresso, UIAutomator, etc.

[8:45]
If you try to test too much or test too specific of a scenario you burn most of your effort using the wrong test for the job and the test will always be brittle and unreliable. (edited)

[8:47]
Integration testing is more fine grained. These tests may or may not run on the device. Once again, they exercise the integration points between components. These tests answer the question, “does my component integrate or play nicely with this other component?”

[8:48]
With these tests you can be slightly more specific but you should still focus on integration. they should be coarse grained in general but can be slightly more fine grained than the functional tests.

[8:50]
That brings me to Unit tests. These are where your fine grained test scenarios live. whenever you are trying to find/fix a very specific bug or exercise a very specific scenario you can rely on these to give you what you need. This is where you would focus primarily to get 100% coverage on the behavior of everything.

[8:50]
I use a vacuum cleaner analogy (which may or may not make sense to you)…

[8:53]
You know how the vacuum cleaner has the big apparatus that sucks the dirt from the floor but this big thing can’t get into all those hard to reach places like in the corner by the door and waaay under the couch towards the back? Well the vacuum cleaner companies usually supply you with attachments like the edger piece, which can get in the tight corners, and the extension piece that lets you vacuum high or in long narrow places.

[8:54]
In the same way your functional tests are like the big apparatus on the vacuum. It’s used for general testing, and broad strokes but there are places that it will not reach.

[8:54]
You should make use of the lower levels of testing for these more specific scenarios. (edited)

[8:55]
Whew, that was a long answer to your specific problem…

[8:56]
To your issue you wrote:
“To test my calculation I thought I’d set a value for display height and width and see if the method returns the expected LayoutParams… I tried different approaches and gave up in the end because all that mocking of Android dependencies” (edited)

[8:57]
You approach indicates that you are attempt to test something very specific at a higher level than necessary.

[8:58]
To test your calculation you should have a unit test which, when given a dimension returns an expected size.

[9:00]
This test can be written in pure Java without android dependencies, which means it can run outside of the container under the JVM using JUnit.

[9:01]
I don’t know if you’ve ever used regular JUnit in your Android project but it something to look into.

[9:02]
What you can do is create a Java module in your project and place your Junit test code there along with the classes that these tests exercise.

I wasn’t finished there. I came back (after coffee) with an example:

Here’s an example. Say you have an app with a single button which, when pressed, makes a network call to a server to increment a counter.

[11:57]
The functional test would load the entire app on the device, deploy the server code to the cloud and launch it, start the app on the device and send a button press.

[11:58]
It would then verify the counter reflected on a text label on the view has been incremented.

[11:59]
(I forgot to mention that there is a textView in the example that shows the value of the counter.)

There are actually quite a few pieces in this seemingly basic example that you should consider

[12:01]
The initial value of the counter needs to be read from the server.

[12:02]
this involves an object that can make a network call to the server, an actual server, an actual network… etc.

[12:02]
A functional test would load two or more of these pieces and test them together.

[12:03]
you could write a test that says:
Given a CounterRequestor
when I ask for the count
then I should get some number

[12:05]
which in Java/JUnit equates to:
CounterRequestor requestor;

@test public void shouldReceiveANumber() {
Integer initialCount = requestor.getInitialCount();
assertEquals(initialCount, 0);
}

[12:06]
This test requires an INTERFACE not a concrete class because you are DESIGNING (the 2nd “D” in TDD) the intention of the app.

[12:07]
The interface would be implemented by some concrete object, say InternetServerCounterRequestor which you could instantiate inside your test in setup…

[12:08]
(also I would write the test before defining the Interface so I could get a feel for how I would use it. I usually use Intellij/AndroidStudio’s Alt+Enter combo to generate the interface after I’ve written a test that shows how I’d use it.) (edited)

[12:09]
then to run this integration test you would need only the CounterRequestor defined, the InternetServerCounterRequestor implementation and an actual running server.

[12:10]
That’s testing the InternetServerCounterRequestor the internet connectivity in your house or office, and the server in isolation without involving your app.

[12:11]
You could then write more tests the specify how you would interact with the count service running over the internet.

[12:12]
The important reason why you would use an interface here is because you want to be able to test pieces in isolation. So now let’s say you want to test the Activity without the internet and without the server deployed…

[12:13]
You could write a test that uses Roboelectric or something to load just the activity and mock the CounterRequestor.

[12:14]
in such a test you could test:
Given a MainActivity with a textField
When it is created
Then it should ask the CounterRequestor for the initial count

[12:16]
you could also test:
Given a MainActivity with a textField
And a mocked CounterRequestor
When it asks the CounterRequestor for an initial count
And the CounterRequestor returns the number 77
Then the textField should be equal to 77

[12:16]
There are a few other moving pieces here as well…

[12:16]
you have the basic button you could write tests for

[12:17]
Given a MainActivity with a button
And a mocked CounterRequestor
When I press the button
Then my mocked CounterRequestor should be asked to send a counter update message

[12:18]
these are all integration tests that test pieces of your solution in isolation

[12:19]
You could probably see a useful pattern here with this example…

[12:19]
The fact that we used an interface allows us to easily vary what/how the counter is implemented…

[12:20]
you could implement a PeerToPeer counter that uses bluetooth instead of HTTP to maintain a counter across devices.

[12:21]
because nowhere in your test code do we specify HTTP, URLs or anything related the change is localized to the implementation of the CounterRequestor

[12:21]
so then this brings me to unit testing…

[12:22]
going through this example (which I am honestly making up as I go along here) you will find that making the network request to the server to get a count might involve XML or JSON parsing…

[12:23]
because usually a web service would return something like:
{
initialCount:0,
error:""
}

[12:24]
instead of just
0

[12:25]
so then you might find yourself needing to do something like parse the response which gets into the micro level of “I have this JSON object with a few keys. I want to design an object that can read the initialCount key and give me its value,

[12:25]
you could do this with a unit test.

There is more where that came from but the above explanation should paint a rough picture of how I see the world. The person I was helping is a developer named Alina from Sweden, I believe. She maintains an interesting blog and has an even more interesting backstory coming from marketing into coding.

P2P Git


Have you ever had your version control server go down just when you were ready to commit some important changes for your team? Did you feel stuck, blocked, or hopeless? This happened to me only yesterday but luckily we use Git for version control. Git is a decentralized version control system which means that you don’t actually need a central host to continue working. While lots of people already know that you can commit, merge, and branch locally without a network connection you may be surprised to know that you can also push and pull changes while the central Github repository is offline using a Peer 2 Peer connection.

Last night I wanted to push changes from my iMac in the office so I could pull them with my Macbook and work from home. Our internal Github repository went offline and I went to Google to find a little trick I’d used in the past. Setting an alias to run a local git server is as simple as:
git config --global alias.serve "daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/"

This creates a git command, serve, that you can run from the command line to launch a local Git server over your current repository.

git serve

I ran this command on my iMac and got output saying something like, “Ready to rumble“. My local git server was ready to accept connections from other computers. On my Macbook I was then able to pull the commits I had just made on the iMac using it’s IP address with the git pull command:

git pull git://10.15.12.15/ feature/newWidget

The “feature/newWidget” was the name of the branch I was pulling. Some output text on the Mac confirmed a remote connection happened and the new commits magically showed up on my Macbook Pro. This same idea could apply if I needed to share my latest branch with a coworker before heading home. I could commit to a feature branch on my iMac and then say, “pull the changes from my iMac at 10.15.12.15”. My coworker could run a similar git pull and see all of the commits appear in their local repository. The alias I used above is read only, however you could also set it up so that coworkers have write access and can push directly to your local git repo as they complete work.

So the next time your internal version control host goes offline don’t sweat it! Run a local git server and share away! I haven’t tried it but I believe this might work with a git-svn setup as well.

How To Suck At Programming #912 – Shave a yak


You started out trying to create a simple Android app when you realized you needed a third party component. You went off to download the component and realized it needed a fix. Since it’s open source you decide to fix it yourself cause, hey, you write code right? To perform the fix you need work on Linux while your laptop has a illuminated fruit on its lid. After you install Virtualbox so that you can install Linux so that you can fix the 3rd party component so you can complete your project you realize you need to download the actual Linux appliance which sends you to Google where you find a link to a torrent. Your search for the best torrent client for OSX is successful and you manage to download the VM which comes in the form of a “.7z” file that your laptop can’t open. You then search Google for “best 7zip client OS X”. Does this sound like you? Hi, I’m Cliff. You’re here because you shave yaks for a living. I’m here because I need to introduce you to my pet Fuzzy, an animal I recently acquired with these two large horn things on the sides of his head. You thought you had a career as a software engineer but things took a tragic turn where people line up for miles at your door with these heavy hairy four-footed mammals each of which is overdue for a haircut.

What is Yak shaving?
Before you go on yet another Google search for the term allow me to elaborate. Yak shaving is the meta-work you encounter in your day job. It’s the work you need to do in order to begin the work you intend to do. It can often times nest itself in other meta-work. In other words, it can be the work you need to do in order to begin the meta-work you need to do in order to start the work you intend to do. This nesting can become several layers deep which is, I guess, why we call it yak shaving. If you’ve ever seen one of these animals you can probably imagine how an initial shave would only uncover the next layer of hair.

When do you stop shaving?
I’d written about yak shaving in the past but the question begs, “when does one stop shaving these animals?” It’s a valid question and rather interesting dilemma because you can easily find yourself unable to tear away from these animals after pulling out the clippers. It’s tough because you get attached… and who wants to leave poor Fuzzy half shaven? His backside is all exposed but he has all this hair up front! Professionally you may find yourself several layers deep in a problem before you realize you’re shaving a yak. At that point you feel you may have crossed the point of no return. This is the point where it costs more to start over with a different approach than it does to complete the task. You want to recognize the situation before it gets that far and put away the clippers! Stop shaving the moment you get a yak!

But how do you recognize a yak?
Sometimes you start with an innocent problem and a naive over-simplistic solution. The solution seems to fit the problem well and everything feels right. Take my example above. Use an open source component to plug a hole in your Android app. Ask yourself up front what happens if the component you’re using also has a hole. Be honest about what it takes to iterate (or change source, build, and test) the component. Sometimes these simple questions can reveal serious assumptions and flaws in your approach.

How do you stop shaving?
Honesty can help avoid the problem but transparency will pull the plug once you’ve started. That means you should constantly communicate your status and goals with your manager and team on every occasion. Managers have schedules and deadlines and don’t get along with these hairy beasts. They will often be the first to unplug your clippers. Divorce yourself from the problem. Early assumptions lead to attachment if only to validate the assumptions. You assume your idea will not introduce much overhead but as the overhead starts to increase you work harder just to validate your earlier (incorrect) assumptions. Being transparent about all the work you are involved in takes strength because you have to resist the urge to trivialize everything. However it allows you to see how far off track you’ve gone while inviting others to dig you out. Instead of saying, “alls I haff duh do is run a VM and do my my compilation there” be honest and say, “I need to download, install, and configure virtual box just to start the project since we have a Linux dependency”. This highlights how the simple act of running a VM has its own pre-requisites, downloading, installing, and configuring. It also gives you a moment to consider how each prerequisite can have its own prerequisites. Some of your colleagues may actually have simpler solutions or fixes for these pre-requisites. When things feel slow invite friends/coworkers.

Yak Hero
Some of us have become so good at yak shaving that we have achieved hero status. In other words we can plow through a series of meta-tasks and nested meta-tasks and make it appear as a single everyday task. We do this by cutting corners where possible. Over time you tend to get a feel for which corners you can cut without it being overly obvious. Taking shortcuts like avoiding a separate project for the component you’re modifying are common. I’ve worked on a number of projects where 3rd party source was included in directly in the project. Another common shortcut is to skip a formal test cycle when modifying source code. These two approaches alone can reduce the time spent yak shaving by 80%. With enough practice you can easily become a yak hero.

In the end it helps to remember there is a cost associated with every choice you make during development. Do not under estimate these costs and do not try to play hero. A yak hero hurts his team tremendously as you merely delay the actual and unavoidable cost of implementation long enough for a team member to assume it. The hero looks powerful and important while the rest of the team that cleans up the hero-slack appears slow and doggish. If you want to suck at programming, play the role of yak hero and shave away! Focus on shaving only the face and clipping a bit around the ears. Your clippers may be dull but, hey, who all will know!