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.