Swift on Android?


SwiftDroid

I spent some time a couple of months ago catching up on Kotlin, the new programming language from Jetbrains. For those who don’t know, Jetbrains is the company behind IntelliJ Idea, which is the technology that powers Android Studio and a whole bunch of other Integrated Development Environments (IDEs) on the market.  Now news has it that the Swift programming language is coming to Android. The headlines I’ve recently seen say that Google may be considering supporting Swift on Android.  I just searched the web and found this pull request from a day ago. Hi I’m Cliff. You’re here because you don’t know which programming language to learn to start your new career as a software engineer. I’m here because I’m having a blast following the excitement around this new Swift movement.

If you’re new to programming this may all sound like Greek to you. After all, who cares about a Swift, Kotlin, and who even knows what’s Groovy these days? You just want to make the next killer app, or possibly get an icon in the various mobile stores for your business, right? Now you have all of these choices. You can currently write Android apps in Java, C/C++, Go, Groovy, Kotlin, and now Swift is becoming a reality? It can definitely feel overwhelming! Let me assure you that each of these options are certainly important and it doesn’t hurt to do a bit of research before jumping in any boat. I’ll explain some of the more popular choices at a high level then briefly speculate on what the introduction of Swift could mean.

Java
If you are brand new to programming you can’t go wrong choosing Java for your Android app. It is one of the more ubiquitous languages out there and it doesn’t take too much effort to master. Java is supported not just on Android, but also on a myriad of platforms from Mac OS X to Windows and Linux. Java has been around for decades and is currently supported and maintained by Oracle. Java would be the best fit for a brand new Android developer because Android has been designed around this language since the very beginning. All other languages require special features, runtime supporting libraries, and/or work arounds. Almost all of the information and tutorials you’ll find online at the time of this writing is based on Java. All of the Android development editors and tools directly support Java as a first class citizen which makes life painless when you create apps. You get features like auto-completions, syntax-aware editing, and more out of the box when you choose Java. With other languages you only get a limited sub set of these features, if any and many of these features may only available as a bolt-on addition provided by a 3rd party. Java programs currently cannot be used on iOS. (Technically there are ways to make it work but these means go far beyond the scope of what most would consider officially supported.)

C/C++
Why on Earth would anyone want to choose C/C++ for writing an Android app? I’ll tell you why! With C/C++ you get raw speed and your code runs directly on the hardware. If you are new to programming you need to understand how many modern programming languages work. Many program languages are compiled (or, in simpler terms, translated) into raw instructions that a computer processor can understand. These raw instructions are actually random collections of 1s and 0s and referred to as machine code. Languages like Java, Groovy, Kotlin, etc. are not actually converted into machine code, rather they are converted to almost a pseudo code and they use a virtual machine. This is like a mini program that runs your translated program. Both C and C++ compile, or convert to machine code and can be loaded and executed directly by the processor on your phone. This not only makes them run faster, but they tend to consume less memory and have the ability to perform tasks that other languages are restricted from performing. Java is actually somewhat exceptional on Android as the virtual machine it runs on is so highly specialized that it can run at near identical the speed of machine code in some cases. (I don’t have benchmarks, I only go off what I’ve learned from various sources.) Still C and C++ give you the option to interact directly with video and audio hardware on the device. These are also the two programming languages on which many other languages are built. One major reason to choose these languages is that they can be used on just about every platform from Android to iOS, to Windows to even non-standard computing devices like Arduino boards. That said, it requires non-trivial effort to create a program that can be ported to different platforms. Still these languages are more complex than many others and are usually considered for specialist tasks, such as high speed graphical or audio processing, low level network data streaming, etc.

Kotlin/Groovy
Kotlin and Groovy are two powerful scripting languages I have been sporadically experimenting with. They compile, or translate, to Java byte code, which is the same code that Java itself compiles to. They both have advantages over Java in that they are more expressive in terms of the amount of code you need to accomplish a specific task. Where Java tends to use a moderately verbose syntax, these languages pack in incredible amount of power in relatively few verbs and commands. They are also quite flexible in terms of the rules of their syntax. One particular example would be the rules around type checking. Some languages, like Java, C, and C++ enforce rigid rules that type identifiers must be used wherever data is sent around or recorded. Also, in some languages the rules around what constitutes a program statement, or single line of code can be verbose and somewhat unfriendly. Some of these rules are somewhat relaxed and more flexible when using either Kotlin or Groovy and they allow you to combine expressions and statements in an intuitive way to make your logic appear more natural. If you have familiarity with one or more languages or are slightly more than a novice it may be to your advantage to give these languages a shot. It should be noted that these languages are not yet supported on iOS.

Kotlin
Kotlin is developed by Jetbrains, the company behind the technology that powers Android Studio. This gives Kotlin a unique advantage over many of the other choices in that it is treated like a first class language. You get all of the tooling support you would expect from a Java based project when you choose Kotlin. Indeed, there would be little to no difference in complexity when choosing Kotlin compared to choosing Java. While there is a slight learning curve if you are only familiar with Java, the Kotlin community offers plenty of online resources to accommodate.

Groovy
Groovy is developed as an open source programming language with a rather large community of active users. It also happens to be the programming language you use when creating creating Android’s Gradle files which are build time instructions for compiling and packaging your Android app. Groovy brings practically every feature from all the popular languages like Python and Ruby. Groovy also has a rather unique advantage in that it actually borrows most of its syntax and grammar from the Java programming language. This allows for a practically nonexistent learning curve. If you know the Java language you already know 90% of the Groovy programming language! The major differences between Java and Groovy are the relaxed rules in Groovy and additional enhancements. While Groovy also offers many of the same tooling support as Java and Kotlin it comes as an add-on and there is not a ton of tutorials or examples currently available. This could change soon as Groovy takes off.

Go
I don’t know much about Go other than it is a new and growing language developed by Google which, I believe, compiles to machine code. It can be used for Android and iOS but the tooling support is limited, to my knowledge. The Go programming language is also open source and backed by a community of extremely active members, many who live, eat, and pay their income taxes with Go. It is said to be a very simple and powerful language, but again, I am only reporting what I’ve heard. You could choose Go if you wanted to run on iOS and Android, maintain a relatively small code base, and have time to go to the movies. I include it in my round up because of its growing popularity especially among enthusiasts. It is definitely something to keep an eye on.

Swift
This brings us to the Swift programming language. Swift is a relatively new programming language created by and owned by Apple. It has recently been open sourced. While only a few of the languages above can be successfully used on iOS, Swift is actually developed specifically for this platform. Its arrival on Android could mean a variety of things such as no more need to maintain two separate code projects for an app that runs cross platform. The beauty of this new language is that is also is an extremely expressive language which compiles to machine code. Indeed you get the best of both worlds with languages like Swift, where it offers the expressivity and flexibility of Groovy, or Python with the direct execution advantages of C/C++. It’s still too early to speculate on how it will work on Android but the news is already creating a lot of buzz. IT will likely take a bit of time for tooling support to be as complete as it is for Java or Kotlin and few people will trailblazer writing cross platform apps with it. However the possibilities are very enticing. Imagine truly writing code in a single language and deploying it to iPhone/iPad/Apple products along with Android phones and tablets!

This post probably has not answered any questions for you. I am just at the beginning of exploring what my next language of choice will be for Android development. As such, I felt I would convey my thoughts while sharing with many of my new found just learning to code buddies. Many of you may be just starting to code and my hope is that this serves as a gentle introduction to what is currently available. For some of my more seasoned coding homies (y’all are still my peoples!) stay tuned because I plan to do a deep dive into a few of these languages and kick the tires to see what is viable. Until next time…

Debugging tips that don’t suck


You write code. You are proud of your career as a coder. Your job pays bills and has certain benefits that make you a rather unique individual. Maybe you’ve published a few apps in the market places. Maybe your software is running a multi-million dollar business. Whatever the case, you have street cred and you feel good. All is right with the world, or is it? Hi, I’m Cliff. You’re here because you think nothing can go wrong in your glass tower. I’m here because I recognize how everything goes wrong in everyone’s tower. Today I wanna talk about some stuff that few people ever talk about.

I’ve been paying LOTS of attention to the lesser glorified parts of computer programming these days, testing, documentation, build systems, but most notably debugging. It’s an obvious blind spot for some. Others see it as a necessary evil. In almost all cases it’s not something that people like to do or even discuss at dinner parties. When was the last time you started a conversation like, “So I was examining the core dump from my segfault and I immediately recognized I had a buffer overrun from assuming my arrays was not zero based in this one edge case…” See most engineers are solution driven. That is to say we are fueled by providing answers. So much so that we often provide answers to questions before the question is even formulated. I think of it as Answer First Development! (We make terrible Jeopardy contestants.) In my career I learned to take an opposite approach to most things we do as programmers. I learned that it pays huge dividends when I do so. Inverting the common practice of striving for a solution means focusing on the problem or the actual question being posed. Emphasizing debugging is one form of inverting our common thought patterns as it forces us to think about the problem rather than race towards the solution.

This post takes a Mr. Miyagi approach towards learning to debug. In the movie, “The Karate Kid” Danielson was in a rush to learn karate so he could beat up the bullies in his high school that were picking on him. You may be in the same rush to learn how to debug your programs. Danielson took the first few lessons seriously because he knew his new sensei had experience fighting. Mr. Miyagi wanted to share this experience with Danielson because he knew it would make him a better person and not a better fighter. I am attempting to share my experience here because it can make you a better programmer, not a better debugger. Danielson became frustrated part way into his lessons because his sensei was not showing him how to punch or how to kick. Instead he was making him wax the cars and paint the fences. I will not show you any magic tools here that make the bugs leap off your screen and run in fear. Danielson confronted his sensei about punching and kicking when Mr. Miyagi called his waxing and painting experience to memory. This was a dramatic scene where Danielson realized he had been gaining experience all along. As you read these tips you may get anxious and feel like you know the stuff already. Bear with me and follow through to the end. I promise the experience will make your bug punching and kicking all the more powerful.

What is Debugging, What is a bug?
Debugging is the science of discovering bugs in your software. To discover a bug you have to understand what a bug is. The first computer bug ever discovered was an actual insect observed in a machine by a woman named Grace Hopper. This makes Grace the 1st and probably greatest debugger of all time! It also gives important context to the topic. Before I digress, let’s define a computer bug. A bug is an unintended or unexpected behavior in a computer application. Because application behaviors are also considered features a bug can actually be thought of as a class of a feature in your software. These are features we don’t expect or don’t want. Sometimes we classify these features as “by design”. Features or application behaviors are created by steps followed by the code in your application. A bug is actually a set of steps or a path through your code that you don’t expect to happen.

A bug is a feature
A bug is a feature

#1 Expect the unexpected!
The best debugging advice I can ever share is to get comfortable with bugs. As a kid I was terrified of bugs. We would get those loud chirpy crickets in our house and it would scare the pajamas off of me! As I got older I got slightly more comfortable with crickets (but then started to see those 100 legged millipedes which made me twice as scared!) Had I been exposed or forced to touch bugs as a baby I would not have been as frightened. I’m saying all this to say that you have to approach every project knowing there will be bugs and familiarizing with this idea from the start. If you think your code will only run down the path you expect it to then you are setting yourself up for disaster. You might say, “Cliff, I do this all tahm! I know my code has bugs, you ain’t sayin’ nothing new!” Hold on a minute because I’m framing the picture for the most powerful of all debugging tips. (I know it’s taking me a while to get to the point but I have this verbosity issue!) All programs begin with two possible paths of program flows: The happy path, or the path you wish your program will follow and the unhappy path or the path you don’t expect your program to follow.

#2 Break your code before it breaks you
Create errors in your code early on. I’m suggestion you create and explore the unhappy path before you design the happy path. The reason is not immediately obvious, but this is the path you will spend most of your time in. The idea is that most programs rarely follow the happy path until very late in development. This means that even though you wish you were on this path, the vast majority of your time developing is follow paths you don’t want. If you had to move and I gave you the option of living in two neighborhoods, one was nice looking with decent schools and the other was crime riddled you would probably spend most of your time getting familiar with the nicer neighborhood. You’d visit the shopping plazas and speak to potential neighbors. Then you would look at your budget and realize you never really had the option of living in the nice place just prior to moving to the slums. You would be uncomfortable, not knowing the dialect, which streets to avoid and the people would all look crazy/funny. If instead, you took the initial visit to the slums instead of anticipating the nice neighborhood, you could make friends with the community, learn how to role through the streets and blend in, and see which side of the street to steer towards to avoid huge potholes. Life would not be what you wished for but you would be comfortable and you could actually thrive. Programming is similar. Run your functions with incorrect input and force your logic down paths you don’t want to get familiar. Meet with the Exception drug lord on the corner and have a talk with him. Get to know his schedule so that you don’t interrupt his business and get on his nerves. I’m making too many analogies, let me share some actual code examples.

XML Parsing

var parseString = require('xml2js').parseString;
function doParse(xml) {
   var data;
   parseString(xml, function (err, result) {
   if(err) throw err;
   data = result;
   });
   return data;
}
var coders = [];
coders.push(doParse("<person name='Clifton' age='40'><company name='GE'/></person>"));
coders.push(doParse("<person name='Stephen' age='36'><company name='Apple'/></person>"));
coders.push(doParse("<person name='Gloria' age='53'><company name='Skype'/></person>"));
//end code

The above example defines a function that parses arbitrary XML strings and converts them into JavaScript objects. It then uses the function to parse various XML strings and push a bunch of person objects onto an array. Dropping this into your an app that needs to create people out of XML would give you a flawless victory. You would go home at night, pet your dog, feed your kids, catch the latest episode of Judge Judy then do a goofy dance just before going to bed at night for a job well done. Now let’s have some REAL fun. Change 11th line by removing the final “/” character in the closing person tag.

coders.push(doParse(""));

If you understand the rules of XML, you’ll note that this creates an uneven or not well-formed XML document where there is an no closing tag. Running the code will now produce something similar to:

Error: Unclosed root tag
Line: 0
Column: 60
Char:
    at error (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:667:10)
    at strictFail (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:693:7)
    at end (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:674:47)
    at Object.write (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:991:14)
    at Object.SAXParser.close (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:157:38)
    at Parser.exports.Parser.Parser.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:503:42)
    at Parser.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:7:59)
    at exports.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:535:19)
    at doParse (repl:3:1)
    at repl:1:13

This is the type of thing that would commonly occur in a project and the type of error that could send shivers down your spine when you’re not familiar with it. The error is telling you what we already expected, the root tag, , is unclosed. Just by making this one minor breakage YOU have taken control and gained the experience of knowing how your program will behave when it gets invalid XML in this location. LEt’s go a little further and break it in a different way.

coders.push(doParse(""));
Here we have intentionally removed the quotes from around the company tag’s name attribute. WE get an exception similar to:

Error: Unquoted attribute value
Line: 0
Column: 47
Char: G
    at error (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:667:10)
    at strictFail (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:693:7)
    at Object.write (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:1380:13)
    at Parser.exports.Parser.Parser.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:503:31)
    at Parser.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:7:59)
    at exports.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:535:19)
    at doParse (repl:3:1)
    at repl:1:13
    at REPLServer.defaultEval (repl.js:252:27)
    at bound (domain.js:287:14)

Nothing surprising here. The error is telling you exactly what mistake you’ve made. (Pay close attention to the detail in the error message as we will go over errors in detail a little later.) Internally your mind is familiarizing with the outcome and making important associations that will become important later on. These examples are stand alone snippets but if they were part of a larger program that included a web page and several other pieces you would note where the program stops, or does not stop. You might also see other errors in your program’s output logs that result from the intentional error. Paying attention to how things behave with random incorrect input can be scary but gives you experience and confidence much like you would get from making a turn down a random road while driving. LEt’s take the example one step further and restore only one of the quotes you intentionally removed:

coders.push(doParse(""));

You now would get an error similar to the following:

Error: Unclosed root tag
Line: 0
Column: 60
Char:
    at error (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:667:10)
    at strictFail (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:693:7)
    at end (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:674:47)
    at Object.write (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:991:14)
    at Object.SAXParser.close (/Users/212474815/dev/nodeexample/node_modules/sax/lib/sax.js:157:38)
    at Parser.exports.Parser.Parser.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:503:42)
    at Parser.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:7:59)
    at exports.parseString (/Users/212474815/dev/nodeexample/node_modules/xml2js/lib/xml2js.js:535:19)
    at doParse (repl:3:1)
    at repl:1:13

This is exactly the same error as the first intentional mistake! What’s happening here is the XML parsing logic is not seeing any elements after the name attribute because there is no closing quote. The rest of the XML is considered part of the value for the name attribute! Even though you have a closing take the parser thinks this is part of the attribute so the error you get is “Unclosed root tag”. Imagine if this were to happen in a slightly larger program with a few more XML tags in the input. A cursory glance at the error then the XML would leave you stuck for an answer. It is extremely easy to overlook the missing quote while counting the opening and closing tags in the XML. In our case we KNOW that we’ve omitted the closing quote and we now know that this can cause an error indicating unbalanced tags. This is an extremely valuable bit of experience as you now know not to take the error message at face value! Now your mind has made another critical association unclosed root tags errors could result from a missing attribute.

You would be surprised how common this type of exception is and how many developer hours are lost chasing issues like this. If you are just beginning to learn JavaScript and XML parsing you can already begin to assume the diagnostic ability of a seasoned engineer wth 20+ years experience with that one piece of knowledge alone! This comes just from removing one character and making an extra round trip running through your program. If you make a regular habit of breaking your code and watching its behavior you will triple and quadruple your ability to diagnose and debug program failures.

#3 Read your error messages
In order to follow tip #2 above you have to actually READ your error messages! Don’t tel Google to read them! Let me ask you a question. How do you feel when reading this message in your console? (Be brutally honest with me! Type your feelings immediately in the comment box.)

'uncaught TypeError: undefined is not a function' on line 49

Do you get a sense of anxiety? Does your muscle memory kick in and pull your mouse towards the swipe to select and copy gesture? (I feel like a Google error messages anonymous group is a good idea!) Fighting the urge to pull the error into the Google search box is an important milestone. Let’s look closely at the error message.The first part says “uncaught TypeError”. This can be intimidating in its own right because it’s uncaught! I certainly wouldn’t want to catch anything and I could understand a novice programmer believing her/his computer is at risk of a virus. The type error also makes it sound obscure. Then you have the following text: “undefined is not a function”. Words like “undefined” and “function” can turn your stomach because you spent all your time defining the logic and you want your program to function! However, let’s put this all into context. The context is actually specified as the last piece of the error message, “on line 49”. (Usually there’s a filename in the error message but I’m just simplifying.) If this were a JavaScript shopping app you might see, on line 49, some code that looks like this:

var salesTax = order.getLineItemsTotal() * .05;

The error is saying something is “undefined”. On this very line you are defining a variable, salesTax, so the salesTax can’t be undefined. Look at the three other pieces on this line, “order”, “getLineItemsTotal()”, and “.05”. The “.05″ is what we call a literal which has a definition by its value which leaves us with a coin flip between order” and “getLineItemsTotal()”. Here’s where it gets tricky as most people would gravitate towards the “order” and question why or how it could be undefined. Go back to the error message. The “is not a function” part of the error message indicates there is a problem with a function somewhere on the line and the only thing that looks like or resembles a function is the “getLineItemsTotal()” part. Putting the pieces together you would gather that “getLineItemsTotal()” is undefined. To resolve and fix the problem you need to see what is in the “order” variable. This variable has to hold a value of some particular type and this type probably does not define the “getLineItemsTotal()” function.

#3b Understand your stack traces
Taking the above example you might have enough information to track trace through your code and find the source of the problem. There’s another piece of the error message that can speed this process. This is called the stack trace. If you’re relatively new to coding you may have never heard of a stack or a stack trace before. The stack is the set of function (or method if you’re in Java) calls that happened up to the current point of your program. When your program has an error you get a message that includes the stack and you can use this stack to trace backward through your code to see what happened.The above error might have a stack trace like this:


uncaught TypeError: undefined is not a function' on line 49
at submitOrder (http://localhost/orderform.htm:49:22)
at handleFormPost (http://localhost/orderform.htm:572:1)
at http://localhost/orderform.htm:234:91

The trace shows you the sequence of events, in reverse, that happened up to the point of the error. The stack follows the error message as a set of lines each pointing to prior function calls. The first line in the stack points you to the line that failed, order form.html line 49, column 22. (An interesting part here is how column 22 points to the start of the getLineITemsTotal() function call.) The next line points to the spot where submitOrder was called. This is within a function named “handleFormPost” at line 571 column 1. The next line points to the code where handleFormPost is call inside the orderForm.htm page at line 234 and column 91. This is possibly in an action attribute of an HTML tag definition. From the top you could see where the error happened inside the submitOrder function and the function, handleFormPost, that called submitOrder. Looking at line 572 in handleFormPost you might see something like:


var orderId = doc.getElelementById("hiddenInputOrderId").value();
submitOrder(orderId);

Here you see on 571, the line prior, we get an orderId from the value of a hidden input field and pass it to the submitOrder function. This becomes the thing the that submit order function operates on. Because this value is a “string” data type, there would be no “getLineItemsTotal()” function defined for it. Looking elsewhere in the code you might find the definition for the “getLineItemsTotal()” function and see that it is part of an object that you could create using the order id. A possible fix would be to create an order object that defines the “getLineItemsTotal()” function using the orderId from line 571. This might look like the following:


var orderId = doc.getElelementById("hiddenInputOrderId").value();
var orderObject = new Order(orderId);
submitOrder(orderObject);

#4 Control your environment
The biggest time sink in any debugging session is identifying random behavior. If you cannot reliably reproduce a problem then you have no hope of fixing it. These are the “It works on my machine” bugs that can send you out the window to the ledge of your building, begging for a second life. When a bug manifests on a particular computer the first thing you must do is identify the environment. Ask questions like which operating system and version is running? What environment variables are set? Which version of the compiler was used to build the program? which machine was used to build the program. which steps were taken to reproduce the bug? It may not be practical to recreate the exact scenario but capturing as much of the problematic environment as possible can save triple time it cost to find the problem. These problems impact seasoned professionals just as much as newcomers. I recently found myself chasing a bug that was related to a particular set of data in a database which lead to me closing a bug multiple times only to have it repeatedly reopened. I ended up changing code that was not related to the original problem and spent a ton of time that I could have saved by re-using the problematic data set.

Identifying your environment is the 1st part of the tip. Controlling your environment is the second equally critical part. If a bug only happens when a certain file exists on the computer, always save the file somewhere safe and restore the file to its original location/condition after you’ve reproduced the problem. Running the program can change the data and the shape of your system. and if you don’t pay close attention you will mistakenly think a recent code change has fixed the problem when actually the problem is only hidden because the state of your system has changed. If you are an advanced programmer then you can take advantage of virtual machines and use snapshots to restore state and assist you in debugging. (I use Virtualbox snapshots all the time and they are a life saver.) If you have no idea what I’m talking about then you can try to rely on a version control tools like Subversion or git to undo your program and file changes while recreating the bug. Don’t let another developer or your manager introduce variables into your environment while investigating. By variables, I am referring to anything that can vary or change, compiler tools, third party libraries, databases, system updates and especially the internet! (Controlling the state of the internet is a slightly more advanced topic I’ll leave until later.) It is incredibly important that you maintain focus and watch the state of the machine, the program source code, any new or changed files and system updates until you’ve identified the problem.

You may feel overwhelmed by the amount of things you need to control when reproducing an error as it can be taxing and near impossible. The idea is not to actually control everything but to observe which things you can reasonably control while identifying the things you cannot. Equally as important as maintaining consistency in your environment is paying attention when things change. While iterating over a scenario that involves multiple steps to reproduce a problem you can get fatigued and begin to unintentionally take shortcuts. There might be a different, not as complicated path through your program that gets to the spot where the error occurs and you might take this path after a few unsuccessful attempts to fix the problem. Avoid doing this as the shorter path may exercise different code that can mask the effect of your latest source changes. You might also super from a particular type of highway hypnosis. It’s where errors start to look like the closing credits of your favorite movie. Have you ever paid attention to anything beyond the starring actors/actresses in the closing credits? Do you know who the “best boy” was in the movie the Titanic? (hint: it was NOT Leonardo Dicaprio!) If you make a change and still see the error message make sure it is THE error message and not a different error message. It is far too easy to assume you are still seeing the same error you just tried to fix when a stack trace whizzes by in the log output.

#E Avoid assumptions
One of my favorite TV shows of all time is House M.D. because of this quote, “When something doesn’t make sense one of your assumptions is wrong.” It is my goto answer whenever I get stuck. The arch enemy of the debugging programmer is the assumption. It robs you of any information you possibly discover and hits a hard reset on your progress. Humans often generalize make assumptions about their environment. Computers are extremely specific. Understanding random behavior that doesn’t make sense means ruling out your assumptions one by one. You often assume you are in fact seeing the same error when sometimes the error changes. You might assume you are performing the same steps as the person who reported the issue. You assume the program is running in the same environment it did yesterday but an automatic update on your computer can cause subtle yet important things to change. Get in the practice of calling everyone of your assumptions into question, even the more obvious ones.

It’s late and I promised to have this post up by the end of the week so I’ll wrap up here. Check back here for tips on dealing with things you have no control over. What I am doing here is laying the groundwork for my next series of debugging tips that don’t suck. You should now be building familiarity of how to properly debug a program which should always start with a question. It takes a bit of patience as you should never rush into debugging looking for an answer. Also note that I have not once spoken about using an actual interactive debugger or any Integrated Development Environment (IDE) tools. This was intentional. Even though these tools are invaluable you want to begin to debug programs without such tools. I imagine how you will feel when you start pulling the bug or problem out of just the error message. Imagine a much more senior engineer firing up a debugger while you’ve already pin pointed the source of the problem. These tips are core everything else that debugging involves.

Debugging your way outta misery


Your monitor is on the floor and your shoe is on the opposite side of the room after ricocheting off the monitor. You family members are puzzled by the noise. Another debugging session has come to a close. “How did we get here? Nobody’s s’posed to be here!” in the words of Deborah Cox. Hi, I’m Cliff. You’re here because you’re no longer wearing your shoes. I’m here to help you regain both shoes and your confidence. Check back later this week for debugging tips that don’t suck!
fhgzVEt

Stuff they taught in Kindergarten… The “D” in TDD


“T” stands for Teddy! That’s good enough for me! Oh Teddy, Teddy, Teddy starts with “T”! Hi, I’m Cliff. You’re here because you wanna figure out what the heck that first sentence is talking about. I’m here because I got side tracked reading an Uncle Bob article which led to my singing a parody of the “C” is for cookie, Cookie Monster jingle. I’m STILL supposed to be working through negative password validation in an Android app but I don’t think I’ll finish in time for a planned demo in 2 days. You might ask “Why am I singing the letter ‘T’ when my title places emphasis on the letter ‘D'”? I’m glad you asked!

I’d like to tell you a story. Once upon a time there was a software engineer who ventured into the land of frogs where everything was green. It was like St. Patty’s day all time which was cool because this guy’s birthday happened to be in the month of March which is a green month. (I never understood why the month of March is always colored green. I suppose it has something to do with the Irish like they all came from Mars and make excellent landscapers or something but I digress.) So this developer *ahem* engineer was living in bliss because there were all of these segmented bars filling up in this magical land, each of which was green. He wanted to share the beauty of this whimsical place with his co-workers but they were all like, “Ain’t nobody got tahm of’ that!” So he goes on living in his shamrock colored habitat for the rest of his life. The end.

Now ask me why did I tell that story? (Again, I like how you ask questions!) Well partly because I sometimes feel compelled to inject random nonsense in the middle of my posts for no apparent reason. However the parody roughly represents my first encounter with TDD, a practice which I am extremely fond of. I want everyone to share in my euphoria but some folks are just wired different I suppose. It’s this wiring that causes some to focus on the wrong letter of the practice. Here we finally arrive at the point. By the way, welcome to the next entry in a series I’m titling “Stuff they taught in kindergarten”. In this series I will cover topics I just learn or re-learned. These are the very same topics my preschool teacher, Mrs. Marzie, covered during my early years. I missed out because I was busy fighting over who gets to play with the Green machine during recess.

“T” is for TESTING. As an avid practicer of TDD I will be the first to tell you that you should never write tests. If you are writing tests you are doing something wrong! When I practice TDD I never write tests or any test code. I hate tests. I despise the word “test”! Ask me how I could feel this way and still actually be a TDD supporter? I’m not a TDD supporter, I lied all this time. I’m a wolf in sheep’s wool. I support the practice but discourage the idea entirely. Let me elaborate.

The word “test” triggers the part of the brain that pulls you away from the most important part of TDD. Check the title to understand where I’m going here. I’ve seen so many well meaning engineers steer wrong because they start to get excited about tests and writing tests and testing their code. (Uncle Bob hits on this point somewhere in the middle of his article and I promised myself I would emphasize this point as the very first part of my blog but I’ve failed miserably!) If you are testing then you are looking for bugs. You are looking for holes in your code and weaknesses. All of this makes absolutely no sense because it implies you have working code. (I need to do an entire other post on the term “working code” because it’s another one of my pet peeves.) When you practice TDD the way it is intended then you don’t have working code. You don’t have broken code. You just don’t have code, instead you have a DESIGN. (Ah, there it is roughly 640 words in and I finally hit the point, design.) With TDD you have a design that you iterate into code that reflects a specific use case. It’s the emphasis on “testing” that turns people away from the discipline of designing. It is the discipline of design that gives TDD its power. When you practice TDD you never write tests, rather you etch a design using a testing framework.

Misconceptions
Before I get too far I want to address some misconceptions. In particular I need to disagree with one point Uncle Bob makes:

It’s true that TDD is not going to help you defend against things you didn’t anticipate.

Bob is well meaning and he wants to play nice with others but this is not entirely true. One of the major benefits of TDD is that you have the ability to incorporate use cases you didn’t anticipate into your design through loose coupling and better cohesion. Th most difficult thing you will ever do as a programmer is change code. When you encounter some use that was unplanned you have to make a change to your code to get it to adapt. If you don’t do TDD then I can guarantee that the change is going to cost more in effort than it cost to write the code initially. In many of these cases you build a work around to adapt to the new feature without actually changing the original behavior. If you do practice TDD then you have already established a predictable pattern of creating, changing, and removing code and the cost remains flat. That means it cost just as much to change existing code as it does to add new work-around code.

Getting back to what I said earlier, you don’t write tests with TDD. A test implies there is code with a potential flaw or weakness. With TDD you use a testing framework to express a particular use of code that has not yet been written. (That’s why it’s called “Test First” because you first code with the testing framework but you really aren’t coding a test you are coding the actual use.)

Another misconception:

the way to address that is to work hard at anticipating as much as possible.

I don’t know why people think working harder is the answer to tough problems. It is actually the cause of the tougher problems. If you are working hard at something then there is a flaw in the design. Also anticipating as much as possible is the opposite of what I like to do. I anticipate only what I feel comfortable anticipating and let the detail emerge as my project matures. As an example, I’ll use this Android app I’m currently building. I stopped working on it about 4-5 months ago and intentionally left holes in my design. I was only concerned about the app paths and getting a prototype working. I recently resumed the project and was able to easily cover some of these holes as I explored new unplanned uses of the code. When I originally wrote the code I just didn’t feel like anticipating these uses because they weren’t important. Now that many have become important I am able to address them with a fresh perspective and solve them in ways I wouldn’t have thought of earlier. Had I anticipated these uses I would have written code that would not be as flexible. It’s hard to describe actually. It’s one of those “you had to be there and live it” kind of moments.

I’m not picking on Uncle Bob… I love his writing/articles, and I’ve unfairly taken a couple of his points slightly out of context to drive a broader point. The point is that writing tests and testing code is not TDD. Designing the proper use of code before you implement it is the core of the practice. This is, by far, my biggest pet peeve with TDD and people who try to explain or defend it. I honestly think we should abandon the word test in favor of something more definitive like “specify”. I like the practice of Specification Driven Design where you specify how you will use/invoke an object with a test specification framework. Still its acronym, SDD, sounds too much like STD and could give the wrong idea. I wouldn’t want to announce I am giving a class on SDD or tell folks I got this SDD thing at work. They’d be all like, “fo’ realz??? Yo, keep ya’ distance!”

That’s all for this installment of stuff they probably taught in kindergarten. I’ll see you next time I get inspired to blab about something.

Things they never taught in Kindergarten


I wish I would have paid more attention when I was 5. I was too preoccupied with the crayons, the PB&J sandwiches and the red cape that the little boy, Quinn, always stole during playtime. I wanted to wear the cape! I wanted to be Superman once in a while! why did he never share? Hi, I’m Cliff. You’re here because you’ve been traumatized in pre-school and beyond. I’m here because I feel your pain…

I learned several things today after hours of painful research. These are things I’m certain they covered in Kindergarten while I was off trying to impress the only other black person in my class (school?) who happened to be a girl. (Yes I had a kindergarten crush…) These are things they probably explained in detail but I was too busy making sand angels by the swing set. These are things that are critical to my success as an engineer, but now I struggle to learn them in my later years. Here’s a few lessons I learned the other day after much trial and error.

Virtualbox Networking

Setting up shared Wifi networking in Virtualbox from an OS X host to a Windows 7 guest is EASY if you were alert shortly after nap time. I’m sure my teacher covered the part where you have to use NAT (Network Address Translation) in your coroporate network unless your overhead wifi routers support bridging. I spent several hours trying to use a bridged configuration while my guest OS was not getting a valid IP only to find out that the in office wifi routers don’t support the type of bridging that Virtualbox was trying to accomplish. I only discovered the issue was related to the routers after connecting my iMac to my iPhone where bridging magically worked on the first try.

You don’t need a bridge!

I had trouble setting up shared folders in Virtualbox (as I always do after initially setting up any VM) so I took to Google. Don’t believe everything you Google! I lost 2 hours because an online tutorial clearly explained that you have to use bridged networking to enable shared folders. THIS IS A LIE!!! My shared folders were not working because of the following point…

Shared Folders

Setting up Shared folders in Virtualbox is a breeze if you take your head out of the lego box long enough to hear Mrs. Marzie, the Kindergarten instructor lecture the room. She clearly would have explained that one should plug in the guest additions CD image after installing the OS before even ATTEMPTING to setup shared folders. (Good ol’ Mrs. Marzie, she always knows what’s up!) IF you want to do anything other than look at the default OS logo or play solitaire then your very next step after installing the OS is to install the guest additions!

You need Java, Python and Visual C++ to do anything reasonable with Electron on Windows

If you are working on a NodeJS or Electron project which is anything more than basic you will need to download the entire internet onto your 256GB hard drive then press build. I’m exaggerating slightly but this is something I intend to write an entire epic series on as it applies to more than just NodeJS projects. Say you want to checkout a project on a brand new laptop (Windows or Mac). You’ve cloned the source and you run the build. The thing that happens next should be filmed… separately… for each developer that undergoes this process. It’s actually good material for a comedy show because the result is so unique and random. In some situations, like mine, you’ll spend hours Googling for separate tools and/or versions of tools. In other situations you’ll spend hours uninstalling separate tools and/or versions of tools. The problem is the developer who created the software probably uses a myriad of tools and dependencies which have accumulated overtime. These dependencies will not be present on a new machine and many will have been updated overtime since the software was first created leaving you with the chore of chasing down approximate matching versions.

My dilemma finally ended with me in a position to partially build my project but the struggle continues. Hit me up if you have any stories from Kindergarten to share!

Many faces of programming


I developed software for various computing devices during my lifetime. When I started I had a certain goal, or end game… if you will. These days I see a vastly different person in the mirror compared to when I started, and that got me thinking, “I wonder how everyone else sees me?” Hi, I’m Cliff. You’re here because you write code and nobody else truly understands what you do. I’m here because I share your story. The following is an abbreviated history of where I started my career and where I currently am. It attempts to capture how the people in my life view me and how those views evolved over the years.

frustration

As a software guy I have always been misunderstood. It’s hard to describe, in words, where the disconnect is. Take the following exchange as an example:

So my wife says, “Go to the supermarket and get me a gallon of milk and if they have eggs get 6.” When I came back she was furious with me asking, “why did you buy 6 gallons of milk??!!!”

I replied, “Because they had eggs!”

The problem exists in the different vantage points the people in my life have. In the beginning of my career I was all about backend work. It was mostly legacy AS/400 but then I got into SQL with DB2 and… well, here’s a decorated description:

(Disclaimer: The author has shamelessly linked to artwork from various corners of the internet to make a point. Any similarities with what you find here and real life scenarios is purely coincidental…)

 

The DB2 SQL Database Programmer

What my mother thinks I do

What the Starbucks barista listening to my conference call thinks I do

What I think I do

What my clients think I do

What I actually do

screenshot

 

 

 

 

 

I eventually moved into General desktop client/server programming. I felt the need to convey my career change to loved ones but I truly don’t think they understood where I was headed.

The General Desktop Programmer

What my grandparents think I do

What my uncle thinks I do

uncle-job-description

 

 

 

 

 

 

 

 

What my wife thinks I do

pacman_game

 

What my neighbor thinks I do

What I actually do

Eventually I moved into more modern technologies landing my first job working for a major dotcom company. I got my first Blackberry, then my first iPhone along with other cool mobile computing toys.

The Mobile Developer

What my older daughter thinks I do

What my younger daughter thinks I do

What my best friend thinks I do

What I think I do

What I actually do

 

…and finally I came to understand that not only do different vantage points color my perceived reality, also my choice of programming language has a huge impact on how I attack problems. The next illustration explains how various programming languages would shape ones overall college career.

Programming Languages in College

 

Android Animation Fun


Merry Belated Christmas!!! I find myself trapped under my Macbook this holiday season and completely captivated by the Android animation system. “I find myself” is sort of a strange thing to say since I’ve never really lost myself. I mean, how can I find myself without involving one of those out of body experiences? If I did have an out of body experience I couldn’t imagine losing myself because I would always know where I last left myself. If myself is not inside my-fleshier-self then I would think that my-fleshier-self would know to stay put until I returned to myself, know-what-I’m-saying? By the way, I’m Cliff. You’re here because you probably did lose yourself on one occasion or another.

You see, not many people are as responsible as I am during out of body experience. Other people would probably misplace their fleshier counterpart while they wander off to the casinos, shorelines and so forth… generally having an awesome time. Then they would circle back, completely forgetting which hospital or state they departed from and… where was I going with the story? Android animation!

I was looking to enhance an app I’m building with animation and when I took a step back I realized I built the beginning of an animation composer. It started from my need to see how the different interpolators behave. I found some source online to visualize interpolation and started to build from it. I had this idea of shape morphing so I created a custom view to see how/what I could do to morph it. My project is somewhat basic. I mean I just started with an activity with an Activity containing animation controls.

A basic activity
A basic activity

I read the values from these controls to make an animator and apply it to a custom view. I then wanted to experiment with orchestrating multiple animations at once or in sequence. For that I needed to repurpose my controls into a fragment so I can create a multi-control list view. Pulling the logic out of my Activity and into a Fragment was somewhat simple using Android Studio. I started by moving the controls in the layout into a separate layout with the extract layout refactoring. This created an includable resource which I wrapped in a FrameLayout. I has to move the animate play button out of the layout with the controls since this would eventually apply to all controls. Building and running on the device confirmed that I hadn’t broken anything while rearranging the layout. I gained confidence to delete the include from my layout. I renamed the activity replacing the Activity suffix with a Fragment suffix and changed the logic to load the newly extracted controls layout. Next I created a simple activity to load the fragment dynamically and add it to a frame layout in the center of the screen.

After confirming the app still worked using the controls out of the fragment I went on to introducing a list view replacing the the included fragment. I figured out how to add fragments as list items in an adapter. I added logic to iterate the fragments in the list and build an AnimatorSet where I play all animations together. Things were broken initially but with a few more tweaks I got the entire thing working again.It is still in its infancy stage but it covers the basics of composing animations and playing them against a custom rounded rect view. You can find my work in progress at Bitbucket.

multiple animation support
multiple animation support