How to suck at programming #FEFE23 donate your day to a bug


It’s a holiday, everyone is partying but you got better things to do. Up early in the morning, you power on your vehicle and head to the office like the model employee you know you are. The wife queries, “Isn’t it a holiday?” to which you mumble, “I gotz deadlinez!” The looming release date of the project you’ve been working on for the past couple of months is beginning to weigh on you like last Thanksgiving’s turkey and yams. Hi, I’m Cliff. You’re here because you suck at time management. On with our story… The air around your shoulders now feels like lead and you can almost make out the text of the actual delivery date as you watch its molecules adhere to one another with each passing hour. Today will be different! You have the entire office to yourself and you will be Mr. Super Productive Programmer Guy ready to close out the 12 top Jira items in 1 heroic effort!

You arrive bright and early, and only dabble on Social media for an hour because, “hey, it’s the holiday and you gotta have some enjoyment!” Finally dismissing further distractions you power up your IDE and go to work! You finally restore the memories tucked away in the soft tissue inside your skull which originated last Friday when you came up with the terrific idea to finish your work over the holiday. “Yes, this is the issue I needed to resolve!”, you verbalize audibly knowing that nobody is in the office to witness your late morning schizophrenia.20 minutes into your effort you hit a snag which sends you off in a whirlwind of meta-problem resolution, also known as yak-shaving. Undeterred you press on, confident because you weird the most powerful IDE on the planet and no amount of yak hair will keep you from making your deadline.

Finally it bites you. The one bug that makes absolutely no sense because the source code was working entirely different just prior to your recent changes. The changes you introduced are the absolute logical equivalent of the original version of the source code. There is no way in the world the behavior should be altered. You have made what is the textbook definition of a safe refactoring yet things have dramatically stopped working! You refuse to use your debugger because everything is TDD on this project. Unit test failure after unit test failure eventually causes you to break down and add log statements, then finally use the debugger. The debugging session leaves you even more puzzled as you Google random log output and red-herring type error codes. You glance briefly out the window and the sun has grown several shades darker and you start to feel your heroic day slip into night. Hour after hour leaves you more stranded, frustrated, and confused as you throw different possible solutions into your IDE, practically reauthorizing the entire project along the way. The emulator that your app runs on mocks you with scorn, the internet feels like its laughing at your pain, you have no other recourse but to throw in the towel but you refuse to give up.

Finally you begin a round of rubber-duck (or teddy bear) debugging speaking aloud each line of source code as you step through your logic mentally. Three minutes into the ducky-debugging it becomes painfully obvious where the problem is originating! The most obvious oversight of a relative URL which should have been absolute! How could you be so blind? Why did you go through all the chaos of rewriting your entire project??? 7 extra characters is all it takes to make the original version of your modifications green bar!

Alas, the day is old and the curtain call has begun on your life as the credits begin to roll announcing the tail end of your holiday. You look at your progress and realize that you have fixed one minor insignificant bug in an area of the app that only you and the night time janitor know exists. (The janitor only know because you spend nights discussing your problems and have been stuck on this issue for months.) Hooray for you! You have devoted your entire holiday towards fixing the only feature in the entire app that does’t actually get used anymore. So if you wanna suck at programming, skip a holiday, go to work, and obsess over that one unused feature. You’ll learn more about the edge cases of the web browser in your emulator and never live to appreciate those precious 24 hours again in your life.

Where are my assets?


I have a quick post today while I work during my holiday. (I don’t want to forget this tip!) If you have an Android app that uses files from the assets folder and you want to inspect whats in the assets folder during runtime use something like the following:

activity.getAssets().list("")

This will get you a list of everything directly under the assets folder bundled with your app. Do NOT do something like this:

activity.getAssets().list("/")

…as this will get you a list of everything bundled outside the assets folder and confuse you. I did this earlier and saw the actual “assets” folder in this list so I thought I could do this:

activity.getAssets().list("assets")

…or this:

activity.getAssets().list("/assets")

Neither which gave me what I wanted. Again, the magic method call is this:

activity.getAssets().list("")

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.