Friday, August 15, 2014

JSON Parsing, Step 3: Design

When people mention TDD, other buzzwords - "Agile", "BDUF", "Waterfall" - start to crop up too. (You can tell I'm the life of the party.) Where I work, "Big Design Up Front" is considered to be a bad word, and you won't catch me supporting it.

But even though I haven't written any code (okay, I wrote a bit of skeleton stuff last time, but that doesn't really count), this article is called "Design"! What gives?

I've done something resembling BDUF once, and it worked fairly well, although I think that was just a fluke. Here, I'm advocating for a high-level sense of design: the sort you get by musing about the question "what is a JSON parser really supposed to do?"

So let's jump back to the example JSON we had before and brainstorm a bit:
{
    "name":"Coding As A Life Hobby",
    "count":3,
    "titles":[
        "Concept",
        "Setup",
        "Requirements"
    ]
}

Here's my train of thought:
  • JSON is represented by six types of JSON Properties
  • That would call for a type, JsonProperty, with six subtypes, StringProperty, NumberProperty, etc
  • Two of the types will have references back to JsonProperty
    • ArrayProperty will contain an array of JsonProperty's
    • ObjectProperty will have a map of strings to JsonProperty's
  • For instance, the JSON above would be an ObjectProperty with three entries.
  • Given an ObjectProperty, I could use reflection to map it to an actual Java object.
  • Somehow I would need to get that ObjectProperty from a string.
  • Obviously, the parser needs to iterate over the characters in this string.
  • It needs to recognize the various words in quotes as strings, and, for instance, preserve whitespace inside quotes while discarding it outside.
  • That could be done by breaking the string up into logical components, or tokens.
  • The first few tokens of the JSON above might be:
    • {
    • "name"
    • :
    • "Coding As A Life Hobby"
    • ,
    • "count"
    • ...etc
  • That would effectively be a lexer (from compilers!).
  • Then the parser would come in and turn the list of Tokens into some sort of Abstract Syntax Tree (capitalized for pomposity).
  • That AST could actually be the JsonProperty objects I mentioned above.
So after [I-don't-feel-like-counting-so-I'll-guess] fourteen bullet points, I've come full circle to a workable solution. Those points have a lot of useful information, but it's not exactly going to be easy to follow if I don't reorganize my thoughts. So let me describe what I think the program should actually do:
  1. Lex the JSON string into an array of Tokens
  2. Parse the Tokens into an ObjectProperty (subclass of JsonProperty)
  3. Map the ObjectProperty onto the specified Java class
There it is! That's my design. Not a detailed mapping of every single class and what it's doing, but a general idea of the main steps that the program will take. Now I can build these three components separately and then link them together at the end.

Last time, I promised you a positive example of how a typical TDD'ed project begins, at least when I'm doing it. Before, I wrote what was basically a full-stack acceptance test, and then ignored it because it was too hard to solve. This time, I'll write a really simple unit test, and then make it pass because it's too easy to ignore.

We agreed to get started with one of the components, so I'll go ahead and start with the Tokenizer.
 @Test
 public void testEmptyString() {
  final Token[] tokens = Tokenizer.tokenize("");
  assertArrayEquals(new Token[]{}, tokens);
 }

This is the simplest use case I can think of: ensuring that when you pass in an empty string, you get back an empty array of tokens.

The commit labelled DESIGN-1 shows the addition of this unit test. If you check out DESIGN-1 and run "mvn package", you'll notice that it doesn't compile, which is obvious since it's using the not-yet-declared classes Tokenizer and Token. This is fairly easy to rectify - in fact, Eclipse will just generate all that for me and save me the trouble.
public abstract class Tokenizer {

 public static Token[] tokenize(final String string) {
  // TODO Auto-generated method stub
  return null;
 }

}

See DESIGN-2 for these changes.

This is an improvement. My code compiles now. But if you run "mvn package" at this point, unit tests will fail, blocking the build. It's pretty easy to see why - the tokenize(String) method always returns null, but the test is expecting an empty array.

How should we fix this? We could start building a state machine, with several different states, and a bunch of conditional statements to move between them. Or we could come up with a brilliant object hierarchy to handle different states and different input characters polymorphically.

I'm getting ahead of myself. Making this test pass is easy. All I need to do is return an empty array of Tokens.

public abstract class Tokenizer {

 public static Token[] tokenize(final String string) {
  return new Token[0];
 }

}

DESIGN-3 has that change. Check out that tag and see "mvn package" yield success.

That was stupid, right? I've basically tricked my idiot test into thinking that my idiot code works. But now I've seen that test fail, and I've seen that test pass. This extremely simple behavior will be a part of this system forever. I don't have to worry about losing the empty-array corner case because of some silly off-by-one error, because as soon as I do, this test will fail and I'll be able to fix it immediately.

Of course, I'm not done yet. I will eventually want to have behavior more complex than a hard-coded return value. But since my code passes the tests, I don't really have a reason to make any more code. I guess that means I need more tests.

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