James Williams

Basics Without Boilerplate: Java the Pain-free Way, Part II

In the last post, I talked a bit in general about we taught introductory Java without advanced constructs in a recent Udacity course. Now let's get to the finer detail of how it all works.

The need for JVM magic

I had a few non-negotiable requirements:

  1. The student must be able to use real constructs and not mocked classes.
  2. The student must write syntatically correct Java code for the portions they write.

The first requirement meant that we needed to look beyond the Java language for testing student code. Java is statically typed so all its classes and functions can't be changed after compile time. That presents a problem when you are trying to check student code that uses Random which by definition shouldn't be reproducible. And we didn't want to do something like having students use a FakeRandom class because they might try to use it outside our course and encounter errors.

Luckily there's a language for the Java Virtual Machine(JVM) called Groovy. Most valid Java is also valid Groovy but a major plus is Groovy's Meta Object Protocol(MOP). It's a mechanism that controls how methods, properties, and attributes are resolved and allowing an application to intelligently respond to method calls. This next bit is impossible in regular Java but is valid Groovy code:

Database.findByAgeAndIncomeAndCity(25, 50000, "Baltimore")

The database object doesn't know anything about the underlying request before I run it. The first time the code is invoked, the lookup fails and methodMissing is called. In methodMissing, the library uses the name to create the query and caches it as a named function. Any future invocations will skip the lookup and use the cached version. The MOP feature we used the most was rewriting the implementation of Math.random() to something that is reproducible.

def randomNumberGenerator

Math.metaClass.'static'.random = {
    if (randomNumberGenerator == null)
        randomNumberGenerator = new Random(42)
    return randomNumberGenerator.nextDouble()

Using Groovy also enabled us to combine what would be separate compilation and execution phases into a single phase.

Generating a class from inside a Java class

The first programming quiz, PrintALine, where a student inputs a single line of code was actually the hardest to create.

There's a library called JavaPoet that allows you to embrace your inner inception and construct functions and classes around student code.

Here's the code that constructs a class for the PrintALine quiz:

def codeBlocksString = """
     System.out.println("Java Rocks!");\n

def javaRocks = MethodSpec.methodBuilder("solutionCode")
            .addModifiers(Modifier.PUBLIC, Modifier.STATIC)

def studentSolution = MethodSpec.methodBuilder("studentCode")
              .addModifiers(Modifier.PUBLIC, Modifier.STATIC)

TypeSpec codeClass = TestUtils.createClass(true, studentCode, javaRocks.build(), studentSolution)
JavaFile javaFile = JavaFile.builder("com.udacity.javand", codeClass).build()

And the output class looks like this:

package com.udacity.javand;

public class CodeClass1471932125479 {

    public static void studentCode() {
        System.out.println("Hello, World!");

    public static void solutionCode() {
        System.out.println("Java Rocks!");

When Groovy isn't so helpful

One feature of Groovy that was initially helpful was joint-compilation. The Groovy compiler can use Java class files as is. But Groovy is too helpful in some cases. Groovy doesn't require semicolons and parentheses are optional when the compiler can infer the intent. In the absence of a return statement, Groovy returns the last statement as a return value. As a result it's easy to accidentally create valid Groovy that isn't valid Java. It doesn't matter if the class was labeled as ClassName.java, in Groovy's mind, it's Groovy code.

All of these features are great if you know the fundamentals and want to save time, not so great if you are a beginner trying to learn as these Groovyisms can sow bad habits. The best and only way we've found to check Java syntax is to compile it and see what happens. From about Java 6, you can invoke the compiler and run it inside an app.

So we receive a String from the student, programmatically create a Java class, run the output through a compile and load it if compilation passes.

Check out the Java Programming Basics course and our Android Developer Nanodegree.

Basics Without Boilerplate: Java the Pain-free Way

For many of us, the first introduction to Java was the classic Hello, World! program. For something that's supposed to show you the most simple thing you can do in the language, there's lots of procedural and ceremonial things you as a student need to know or ignore. There's access modifiers, classes, functions, arrays and more.

Java HelloWorld Animated GIF

That's a lot. Some students can ignore the foreign concepts and others can't cope with not knowing. In their defense, it is a weird feeling to have parts of the most basic program be unknown and hard to understand. So when we were discussing making this course, I asked, "What if we didn't have to teach students about the advanced topics present in a Java app until the moment they needed them?"

So our version of Hello, World! looks like this:

In-Class IDE Animated GIF

As the student progresses through Java Programming Basics and the upcoming course on advanced topics, less and less code is written for them. By the end of the course, students will be really confident with general Java syntax, control flow, looping, and functions.

Check out the Java Programming Basics course and our Android Developer Nanodegree.

In case you were wondering what actually gets executed when the student hits "Submit," here's a sneak peek. I'll talk about some of the technical details in a future post.

A Sponge, A Starfish, And The Apocalypse

Whilst in Chicago for a totally different reason, I happened to flip on the TV and saw a commercial for The Spongebob Musical. I thought, "this could be really good or really bad." I checked BroadwayInChicago.com and tickets seemed to be sold out for the week. Next, I checked the TodayTix app on my phone and not only did they have seats available, they were only $39 (+ fees). Definitely worth the risk if it turned out to be bad. I ended up purchasing a ticket for night three of the pre-Broadway previews, night three!!! Opening night would have been a better get but seeing it in previews still garners theatre geek bragging rights. The seats were pretty awesome as well, Row G in Orchestra, pretty much dead center. Shout out to TodayTix.

The Spongebob Musical Playbill and Ticket

The Premise

It's just a normal Bikini Bottom Day until a series of events occur that threaten Bikini Bottom. Will Bikini Bottom be saved? Can Spongebob, Patrick, and Sandy save the day?

The Music

The music boasts a cadre of Grammy winning songwriters and artists ranging from pop to gospel to hip hop/soul to rock. I'm serious, look at them ...

The Spongebob Musical songwriters

The songs balanced the iconic style of the original artist while fitting into and driving the story forward. "BFF" is so iconically Plain White T's that I wondered for a second if they just changed the lyrics of an existing song.

The Sets, Cast, and Costumes

The set was in many cases what I'd call an "Under the Sea" prom theme on a shoe string budget. Whereas it would be a fail at a prom, the cheapness made everything feel more cartoony. I marveled at the creativity in unconvential materials. I wouldn't have thought to make a coral reef out of pool noodles or a jelly fish from an umbrella. There was also a sort of Rube Goldberg machine that drives part of the story. As Dolly Parton said, "It costs a lot of money to look this cheap."

That creativity also extended to the cast costumes (sorry no pics, rules is rules). Even though some were somewhat literal translations from the cartoon versions, I mean there are only so many ways you can do Spongebob, there were little twists here and there were unexpected. Sandy the Squirrel was portrayed by a African-American actress with a fro. Not absurdly sized...kind of Pam Grier in Coffy. Just enough to hint at the helmet though wouldn't be feasible for a human jumping and dancing around. Another costume twist was the a crustacean of some sort whose shell was fashioned from traffic cones and a very colorful sea anemone. Mr. Krabs costume was pretty simple, just died hair and oversized boxing gloves, but it was one of the most successful. Pearl Krabs threw me for a loop but that's forgiven for several reasons: (1) I'm not an uberfan of the show and she's a relative minor character, and (2) the character is a sperm whale, there isn't much that you to mimic the character as a humanoid without greatly limitly the confort of the actress.

Spongebob Set

The humor

There's lots of classic Spongebob slapstick / physical comedy but there's also layered humor peppered in the show for the adults. It's a bit weird laughing at the sexual inneudo between Karen and Plankton whilst surrounded on two sides by kids laughing at the more accessible joke that came seconds before.

Should I go see it?

I'd say if you are mildly familiar with the cartoon and don't abhor it, you'll have a good time. I've watched maybe 5 episodes of Spongebob from start to finish and my cheeks were hurting from smiling and laughing so much. There's a tap dance number that brought the house down due to the skill and ermm challenges of our characters costume. It was a full-on Rockettes/A Chorus Line number. I loved the show so much if it weren't for work, I would have gone and seen it again.

Spongebob Set - Animated GIF

Books I Read In 2015

We're already a quarter into 2016 and I'm just getting this list out. I read lots of good things and some that were just meh. Here's last year's list.

Don't Make Me Think: A Common Sense Approach to Web Usability (3rd Edition) by Steve Krug. Don't Make Me Think was a part of my self-study whilst preparing for my Material Design course.

I've been reading a lot lately about design these days. Don't Make Me Think: A Common Sense Approach to Web Usability (3rd Edition) is something I've finished that has got me thinking about how I approach how I present information to my users.

Though focused primarily on web design, much of the content applies to mobile app design. It aligns with my current Material Design work in trying to present information in an intuitive and glanceable way guides the user from point A to point B with little turbulence.

The section on accessibility spawned an "A-ha" moment. A cluttered site with a confused design is frustrating to both sighted and blind users. I can't say that every design I do will strive for total accessibility but I'll try to tackle the low lying fruit like using the label tag in forms, alt text for images, and using a decent contrast between text and the background.

Don't Make Me Think is IMHO essential for any developer that wants to dabble in design.

Hooked by Nir Eyal.

Zero to One by Peter Thiel.

The One World Schoolhouse: Education Reimagined by Salman Khan‎.

I believe I enjoyed these somewhat when we read them for the work book club but I can't really think of anything from them that I apply to my every day work.

The First 20 Hours:How to Learn Anything.

I liked the concept of The First 20 Hours but the implementation was kind of painful. The first three chapters were pretty useful but the last six were either way too slow, like the chapter on Programming and Touch Typing, or so left field that they were boring (Ukulele, Wind Surfing, and Yoga). Given the recent buzz about AlphaGo, I might visit the Go (game) chapter.

The Hunger Games by Suzanne Collins.

Catching Fire by Suzanne Collins.

Mockingjay by Suzanne Collins.

I had a couple of long flights panned and decided to start the Hunger Games series. All are great reads, though I like the first and second books better than the third. I hadn't watched the movies before reading each book so it was fun seeing how they adapted things. They did a good job IMHO.

Off-Course: Inside The Mad, Muddy World of Obstacle Course Racing by Erin Beresini.

As you may know from my Instagram, I do a lot of obstacle course runs. Off-Course is a feel good book about the craziness and pain that I and a growing number of people all over the world pay to endure. If you want to know a bit more about how OCRs work, check out Off-Course.

Listening Brands: How Data is Rewriting the Rules of Branding by JR Little.

Probably the best work related book I read this past year. I got it on a whim from Kindle Unlimited and have referred it to everyone at work that will listen. :D One of the basic premises of the book is that you don't get to 100% decide how your brand is defined or seen by the general public. Listen and embrace what your communities say/think and profit.

Taming Google Calendar With Org-Mode

Over the past few weeks after setting up Org-Capture, I've been spending more of my raw time in Emacs but would have to context switch to a browser to look at my calendar events. That's no good. Luckily, we can solve this egregious problem by using a combination of Org-Capture, Org-Agenda, and Emacs-Calfw. Don't worry, the setup isn't as complicated as it sounds.

Setting Up Org-Capture

If you don't use Orgmode for your TODOs, you definitely SHOULD. Org-Capture allows you to quickly enter notes without a big context switch. You can even make templates for different types of data. I use Org-Capture templates for TODOs and logging food and exercise. The following snippet sets up the default location to store the notes you log and defines a shortcut as C-c c. I like to know what time I finished a task so org logs that as a property when the task is done. Lastly, I have template for TODOs. The first argument is the shortcut to log a TODO, in this case C-c c t. The other arguments specify the file where the TODO will be saved, what heading in the org-file it will be logged under, and the format of the template. Check out these links for more info about Org-Capture:


(setq org-default-notes-file "~/Dropbox/Org/notes.org")
(define-key global-map "\C-cc" 'org-capture)

; Log done state in TODOs
(setq org-log-done t)

; Set Org-Capture templates
(setq org-capture-templates
    `(("t" "todo" entry (file+headline "~/Dropbox/Org/notes.org" "Tasks")
        "** TODO %^{Task} %?")))

Setting Up Org-Agenda

Org-Agenda gives you multiple views to visualize data in Org files. These don't have to be all in one location and can be spread across multiple areas. I have one file for my calendar data and another for my TODOs that I set earlier. Org lets you schedule your TODOs with C-c . and these will show up on your agenda when you hit C-c a.

(setq org-agenda-files (list "~/Dropbox/Org/notes.org"
; Set key combos
(define-key global-map "\C-ca" 'org-agenda)

Emacs Calfw & Org-Gcal

The last piece of the puzzle is Emacs-Calfw (https://github.com/kiwanami/emacs-calfw) and its org-gcal integration (https://github.com/myuhe/org-gcal.el).

Calfw in Emacs

Calfw uses our Org-Capture and Agenda setup to give us a new calendar view. We can view an individual day or week and its associated events. Open a day's agenda by selecting it and hitting the space bar. Drop the following in your .emacs setup wherever that lives.

(add-to-list 'load-path "~/.emacs.d/emacs-calfw")
(require 'calfw)
(require 'calfw-org)

So far we can grab scheduled TODOs and see them populated on our calendar by opening an agenda buffer with C-c a and then running M-x cfw:open-org-calendar. For Google Calendar integration, you need to feel comfortable with the Google Developer Console. Follow the org-gcal setup instructions(https://github.com/myuhe/org-gcal.el) to get a client id and secret looking somewhat like the following to drop into your config files.

(require 'org-gcal)
(setq org-gcal-client-id "something.apps.googleusercontent.com"
      org-gcal-client-secret "something"
      org-gcal-file-alist '(("calendar@something.com" .  "~/Calendars/schedule.org")

As you can see, org-gcal dumps everything into an org file that Org-Agenda is aware of, which emacs-calfw knows about and it's turtles all the way down.

Refresh your listing of calendar events with M-x org-gcal-fetch. Sometimes you'll get prompted to refresh your OAuth token M-x org-gcal-refresh-token.

Org-gcal populates your org file with the event's location, video conference links, and a link to the event on GCal. With the day's agenda open (Space), you can see the properties of an event by moving your cursor to it and hitting TAB which takes you to that entry.

Add a entry to that file and run M-x org-gcal-post-at-point and an event will be created for you.


I don't generally use org-gcal-sync and only fetch events from my calendars. org-cal doesn't have a way to accept events or add other people to a calendar invite. That works for me because I don't generally reject things and merely go to the event or not.

You can not reserve rooms through org-gcal.

My next task is to setup a snippet to refresh my calendars on an interval.

What #2015BestNine can tell you about your brand

I just finished reading a great book called Listening Brands: How Data is Rewriting the Rules of Branding and the recent hashtag going around #2015BestNine got me thinking about what it means for brands.

The basic premise of the book is that the old inituition, big idea, "talk at the customer and make them like you" point of view in advertising is old fashioned. Instead, you should listen to your customers and engage in a conversation with them proving that you provide value for them and deserve to be a part of their lives. One way to do that is with data.

So what does this have to do with #2015BestNine? #2015BestNine gives you a mini-dataset that you can base some limited conclusions on. For example, do certain filtered photos perform better than others? Is there a certain type of photo that performs better than another?

I will caveat that clarify of the data goes down as the volume of photos go up. A high school friend of mine is a model and instragrams alot, taking many shirtless photos in his underwear. His best nine was filled with these and while it gives a strong signal that his followers love to see him with his shirt off, the sample size is too small to give any other insights to his other photos.

Below is my 2015 Best Nine. I only started sharing on instagram about 6 months ago with an average posting schedule of once every 3-4 days(~57 posts) with a small amount of followers(~ 90). So 9 posts will be statistically significant as it is roughly a 15% sample.

My Best Nine

My Best Nine tells me that people see me as athlethic. Seven out of nine pictures relate to fitness, running, or obstacle course runs. If I were trying to maximize likes with this group, I would endeavour to post more pictures from runs and maybe think about what peripheral stuff I could post (going to the gym, etc). One of the best nine is a darkly lit video of myself doing burpees in front of a Christmas tree from four days ago. I think it was either the timing of the post or the novelty of the Christmas tree that made it perform well.

The only data that is too small is no data al all.

Using Kotlin with libGDX

I've been kind of fascinated with Kotlin recently and when I learned of the #libGDXJam, I decided to use it for whatever game I'd end up creating. It turns out that it is remarkably easy to add Kotlin support to a libGDX game.

1.Generate your game without the html target.

The JS sources are generated with Google Web Toolkit which operates on Java source files. Because your files will be in Kotlin, the GWT compiler will complain about them. This is a bit of a bummer but I'd wager that you are more likely to deploy to desktop or mobile anwyays.

image of gdx-setup

2.Tweak your root level build.gradle file.

In the buildscript section, you'll need to add the kotlin-gradle-plugin on the classpath. This is so that the core project will be able to find it.

image of gradle buildscript

In the core project, add apply plugin: "kotlin" and the compile dependency as follows. You can add a variable in allprojects.ext for the kotlinVersion or hard code it here. Either works. Use the same version number from this page for both the kotlin-gradle-plugin and kotlin-stdlib versions

image of gradle core project dependencies


One thing you might notice is that sometimes the Android build gets confused and says it can't find your game/application file. To fix that, go to the AndroidLauncher file and make sure it has a proper import for your game/application.

If you'd like to learn more about making 2D games with libGDX, Udacity has couple courses and a nanodegree program, check them out.

Material Design at BABBQ15

This past week, I represented Udacity at the Big Android BBQ and gave a talk on Material Design. It was based on the Udacity course I launched earlier this year with Roman Nurik and Nick Butcher.

Check out all the recorded talks here.

Books I Read In 2014

Just like last year, here's my annual list of all the things I've read. I've omitted the programming books because I rarely read one cover to cover.

Moneyball: The Art of Winning An Unfair Game by Michael Lewis.

Moneyball was by far my most favorite read of the year. It really spoke to the math geek in me with how the Oakland A's staff used statistics to predict performance. Before reading the book, I had regarded baseball stats as something that the announcers quote to fill up time or appear smart. I'm considering doing my own mini-exploratory data analysis with some of the stats that are freely available online.

Mindset: The New Psychology of Success by Carol Dweck.

I noted earlier in the year that I listened to a podcast where Carol Dweck was interviewed(). The book made me think a lot about the students that take my Udacity courses and how to encourage them in ways that make them want to succeed.

Brazil's Dance with the Devil: The World Cup, The Olympics, and the Fight for Democracy by Dave Zirin.

Great background on the unrest that occurred in the run-up to the World Cup and what is coming in 2016 for the Olympics. I'm finding it harder and harder to justify having these big ticket events in Third World countries as they often have to screw over their economy and future to run a two week or one month event.

The Sketchnote Handbook: The Illustrated Guide to Visual Note Taking by Mike Rohde.

Being a Course Developer is largely about distilling complex ideas and concepts into something the students can easily understand. I happened upon sketchnoting as a way to improve the my abilities in conveying ideas with drawings. The Sketchnote Handbook is presented like a design book giving you the essentials to present ideas with drawings text using color, proportion, flow, etc. It's a great read for anyone that does presentations or needs to take notes. I really wish I had known about sketchnoting when I was in school.

The Verbal to Visual Notebook by Doug Neill.

Verbal to Visual is a workbook demonstrating sketchnote principles. There are exercises to complete as well as templates to use when you are starting to sketchnote. The templates have helped me organize how I might take notes in a conference talk based on the format (Is it a lecture? Q&A? Panel? etc). V2V is the perfect companion to The Sketchnote Handbook.

Unlabel: Selling You Without Selling Out by Marc Ecko.

Ecko tells the story of how he took $5000 and turned it into a billion dollar brand. What was refreshing about it was that he framed each event with how he remained true to his brand and creativity or not. Unlike other semi-autobiographical books I've read, the missteps were discussed in as much detail as the successes.

Five Stitches: A coming of age psychological clusterfuck by Jason Donnelly

Five Stitches was the last book I finished this year and the most surprising. I read Jason's other book Gripped on the recommendation of a friend. Five Stitches is much more dark than Gripped. It deals with mental health and robbery capers.

Fluent in 3 Months: How Anyone at Any Age Can Learn to Speak Any Language from Anywhere in the World by Benny Lewis.

This is a nice book to read if you don't already follow Benny Lewis' blog and are struggling with your first foreign language. It is probably good for some but I didn't get that much out of it in additional to what I already know.

Spartan Up!: A Take-No-Prisoners Guide to Overcoming Obstacles and Achieving Peak Performance in Life by Joe De Sena.

This was one of my health related reads of the day. Written by the creator of Spartan Race, with which I've become a bit addicted, I wouldn't call it a guide per se. It's more so inspirational semi-autobiographical book.

Men's Health Your Body is Your Barbell: No Gym. Just Gravity. 28 Days to a Lean, Strong, More Muscular You! by BJ Gaddour.

This was the second of my health related reads this year. I've been fascinated by bodyweight workouts ever since hearing about Herschel Walker's workout plan from my dad as a kid and more recently having seen Barstarzz videos on Youtube. Great book by a motivating guy, hope to put it more into practice in 2015.


Mindset Sketchnote

This past week, I listened to one of my favorite podcasts, The Bryan Callen Show where they interviewed Psychology researcher Carol Dweck about her book Mindset: The New Psychology of Success. I used the podcast as an opportunity to experiment with sketchnoting, also known as visual notetaking. Here's the sketchnote of the key points from the podcast.

My rowmate on the plane saw my doodling and when he learned that it was just a podcast about the book and not the book itself, he almost commanded me to read it. Am starting now.

Mindset Sketchnote