Tuesday, July 29, 2014

JSON Parsing, Step 2: Requirements

"First, you must create the universe"
--Carl Sagan
Strictly speaking, without a working universe, writing a JSON parser would be difficult. But beyond having a universe, it might also be helpful to know what JSON actually is.

This is a JSON object:
{
    "name":"Coding As A Life Hobby",
    "count":3,
    "titles":[
        "Concept",
        "Setup",
        "Requirements"
    ]
}

JSON is a lightweight, human-readable format for encoding data, used by basically any web service that wants to be taken seriously. A JSON object contains a bunch of key/value pairs, where the key is some string, and the value can be a JSON property of any type. The types are:
  • String - Any sequence of unicode characters
  • Number - Can be an integer or floating point, and must be expressible using "e" notation (like 6.23e23)
  • Boolean - true or false
  • Array - An ordered list, delimited by square brackets '[]', of JSON properties, each of which can be any of these six types
  • Object - An unordered set of key/value pairs, like I mentioned above
  • Null - Just null
Ideally, I would like my JSON parsing library to map this JSON to a Java object that might be defined like:
package com.themutatedshrimp.json.example;

import java.util.Arrays;

public class ExampleObject {

 private final String name;
 private final int count;
 private final String[] titles;

 public ExampleObject(final String name, final String... titles) {
  this.name = name;
  this.count = titles.length;
  this.titles = titles;
 }

 public String getName() {
  return name;
 }

 public int getCount() {
  return count;
 }

 public String getTitle(final int index) {
  return titles[index];
 }

}

Where the values as defined in the JSON string get mapped into the instance data of this object.

Since I will be using this object in my unit tests, I will introduce it into the code base as commit REQS-1. While I'm at it, I'll also go ahead and remove Maven's gifts - App and AppTest, since all they're doing is adding clutter.

My end goal is to pass a JSON string, like the one I mentioned above, into some JSON processor object, and have it spit out an ExampleObject with the fields populated.

Or in other words, this unit test should pass:

 @Test
 public void testExampleDeserialization() {
  final String json = "{"
    + "\"name\":\"Coding As A Life Hobby\","
    + "\"count\":3,"
    + "\"titles\":[\"Concept\",\"Setup\",\"Requirements\"]"
    + "}";
  final JsonProcessor processor = new JsonProcessor();
  final ExampleObject example = (ExampleObject)processor.deserialize(json);

  assertEquals("Coding As A Life Hobby", example.getName());
  assertEquals(3, example.getCount());
  assertEquals("Concept", example.getTitle(0));
  assertEquals("Setup", example.getTitle(1));
  assertEquals("Requirements", example.getTitle(2));
 }

The commit REQS-2 has this unit test added, and just enough code to make the code compile, namely a skeleton JsonProcessor class, which I will probably want to rename at some point.

If you check out REQS-2 (by running "git checkout REQS-2"), and try to build (by running "mvn package"), you will notice that the unit test fails, blocking the build. That makes sense, because this test asserts a very specific behavior that doesn't work yet. But now isn't the time to make this test pass either, because I honestly have no idea how to do that.

What I've done so far isn't TDD, by the way; this test is far too complicated. Before this is over, I'll show you a positive example of TDD so that you can see the difference.

All I did here was establish one of my requirements, in a form that happens to be a test. It's okay that I did this, but I'm not going to make the test pass right now. Instead, I will add the "@Ignore" annotation, so that JUnit doesn't try to run this test. Once I think my code is ready for this test, I'll drop "@Ignore", but that will be a while.

Check out REQS-3 and run "mvn package", and you'll see the output
Tests run: 1, Failures: 0, Errors: 0, Skipped: 1
Sanity is restored, but the existence of skipped tests will serve as a warning that we still have work to do...

JSON Parsing, Part 1: Setup

One thing I've noticed is that when you actually write code, you ask questions that guide the flow of the project. Questions like "What language should I use?", "What should I use to manage my builds?", "Why am I spending my evenings writing about TDD on the internet?", etc.

For language, I settled on Java for a few reasons. The languages that I know the best are Java, C, C++, and Python. Java gets one point for being the language that I'm most familiar with, but it also gets extra points over Python because I like the security afforded by a competent type system, and over C because the Anti-If thing that I'm trying doesn't work so well when polymorphism is nonidiomatic. The choice between Java and C++ was largely aesthetic, although Java's ability to use reflection is useful for object-construction exercises like JSON-parsing.

From there, I chose Maven as my build system, mainly because everyone has strong opinions about it and I've never used it. I don't really anticipate learning much about it in this exercise, because one of my main goals is minimizing external dependencies, but it's always worth a shot.

And that leads me to setup. I use the command below to generate a Maven repository:
    mvn archetype:generate\
     -DgroupId=com.themutatedshrimp.json\
     -DartifactId=json-parse\
     -DarchetypeArtifactId=maven-archetype-quickstart


That creates a project with some classes called "App" and "AppTest", which don't really do anything. After running Eclipse's auto-formatting on them to remove the annoying whitespace at the ends of the lines, that comprises my first commit, at the tag INIT-1.

(Note: the tag INIT-0 is the state of the code at the beginning of this post. INIT-1 is the first actual commit, and INIT will be the merge commit back into master. I'll be following this convention in order to easily refer to individual commits on the repository in Github.)

The rest of the "INIT" commits are a few other maintenance tasks to clean up and prepare the repository for actual coding, such as:

  • INIT-2: Adding a plugin to make Maven-Eclipse integration use the right version of Java
  • INIT-3: Upgrading to JUnit 4.11 and reformatting the code to match my style
  • INIT-4: Adding a .gitignore file.
And now we're ready to start!

Monday, July 28, 2014

JSON Parsing, Step 0: Concept

It's amazing the sorts of things people get riled up about. Politics I can understand because they don't care about the poor and you want to take away my hard-earned to fund abortions! Even sports teams because noooo how could the team from your hometown make the ball go to that side more often than the people from my hometown made it go to this side!!!!! But TDD? Really?


Seriously, all this, over when you write your tests?

Granted, one of those people is probably right (and by the end of this article, you'll know which one I agree with). But both of them are wasting their time, because all they're really doing is standing on either side of an isle calling each other extremists while sounding fairly extremist themselves.

I guess I'll ruin the suspense. I love TDD. I've practiced it for a little over a year, and I've found that I have a much easier time producing code faster and of higher quality when I practice TDD. And instead of shaming you for not following TDD, or melting down a building or something, I'm going to use this series of posts to show you, my valued reader, exactly what my TDD-style process looks like.

And if you don't like it and decide that it's not for you, then that's probably fine.

Moving on, have you ever heard of JSON? Probably, but just in case you haven't here's the Wikipedia article on it. The summary is that it's a nice human-readable, but also computer-readable, format that's often used for transmitting generic data over various protocols. For instance, a lot of HTTP payloads are JSON strings unless they need to be HTML for some reason.

A JSON string might look like this:
  {
    "blog":"The Box of Sand",
    "article":{
      "title":"JSON Parsing, Step 0: Concept",
      "length":158941
    }
  }

At its core, it's just a map of string keys to JSON objects, which can themselves be numbers, strings, maps, and so on. For reasons I won't go into right now, I tend to dislike using third-party libraries, and prefer to re-invent my own wheels when I can, especially when it can be a learning or teaching experience. So what could be more useful than building my own JSON-parsing library! (Don't actually answer that question)

Moving on, have you ever heard of the Anti-If campaign? If not, here's their official website.

Sounds crazy, right? Until you realize that you spent the entire week fixing a bug that would have taken three minutes to solve if it hadn't been hidden behind seventeen if-statements, some of which don't need to exist and the rest of which could be moved out to named methods or something like that.

My understanding is that it's possible to write code with no if-statements - that an if is a sign that you should be using polymorphism instead. I've never followed a rule like that before, but something as user-inputty and process-y as JSON parsing seems like an interesting place to find out just how feasible it really is to avoid if's.

And that brings us to the mission:
  • Build a JSON Parser
  • Using TDD
  • With no external libraries
  • And wave GIANT red flags if I ever see an if statement
I'll keep an ongoing table of contents here, and you can look at the code and the commit history at https://github.com/joshlarson/json-parse.

Posts So Far