Can you get a green bar?


Here’s a little homework exercise in Test Driven development. (It’s actually my sneaky way of getting you to do my work for me!) Short story first. I was working on something this morning and I came to a point where I couldn’t think of how a particular piece of code would work or even if it would work. I knew I could probably use regular expressions to do what I wanted but I’m no good at regex and as a result was a little unsure. I called on (via IM) my Regex partner in crime, my buddy on the other side of my cubicle wall, and asked him. (It’s funny how we sometimes never exchange words in our office, rather relying on IM even when sitting right next to each other.) The instant message bleeps and blips went like this:

Me: I need regex help again

Him: Oh yeah?

Me: I want a method that will take a pattern and a string, and return the String plugged into the pattern.

Him: I see

Me: In other words:
resolveWithPattern(“com.company.processors.(1)Processor”,”MyCustom”)
should return com.company.processors.MyCustomProcessor

Me: As a matter of fact… can you make this test pass?

And so I now ask you the same question. Consider it a little excercise in Test Driven Development and what I’ve heard referred to as intentional programming. If you’re not too familiar it may be a refreshing change. I strongly urge you to use either Idea or Eclipse (or possibly Netbeans) for the excercise as these IDEs support intentional programming. The idea is to take the test code below and try to make it pass.


public class PatternResolverTest extend junit.framework.TestCase
{
   public void testPatternResolver() throws Exception
   {
       assertEquals("com.mycompany.processors.MyCustomProcessor", 
               new PatternResolver().resolve("com.mycompany.processors.(1)Processor", "MyCustom"));
   }
}


First you’ll need to compile it. Don’t do anything other than copy the code into a new project and try to compile. You’ll notice it depends on a class that is not in your classpath. You don’t want to right click in your project explorer or invoke any add new wizards. Instead you want to invoke your IDE’s intentional assistant. (How do I know so much about what you want? It’s because I’m in your head, maaan!) In Eclipse you hit Ctrl+1 in Idea you hit Alt+Enter. That’s where the magic begins. Let your IDE stub out the class that doesn’t exist. Don’t add any code to the stubbed out class. I mean it. Not one if/else statement. Not one method call! Nothing! Recompile the test and compile the stubbed class. Now immediately run the test! “Why would I run the test when I know it’s going to fail??!!” Because silly! You don’t know it’s going to fail! If you practice my approach enough times you will no doubt ecounter times where you will swear a test is going to fail because you haven’t added anything but instead you get a green bar. Enough talking back! Have you run the test yet? What color was the bar? Purple???!!! No, cuz… you’re using the wrong unit testing framework! Download JUnit. (If you’re savvy enough you can take a stab at TestNG instead.) What color is your bar now? It should be red before we continue. What’s that? You don’t have a bar? You have a trapezoid? JUnit cuz, get with the program!

Alright, next step. Once you have a red bar make it turn green. Hey, hey, hey, hey!!! What are you doing with that green marker? Don’t do that! You’ll ruin your monitor! Make the bar turn green, don’t scribble over it! Is it green yet? Of course it isn’t because you’re busy reading and not coding anything! Once it turns green kindly paste the stuff you have between “public class PatternResolver {” and “}” into the comment section below. I thank you in advance for your hard work on my problem. By the way, if there are any problems with assumptions in the above TestCase feel free to post corrections. Holla’ holla!

10 thoughts on “Can you get a green bar?

  1. 1) Does Eclipse really stub out the class for you? I had to do an extra step and actually add an empty method definition for resolve to the stubbed class before I could run a JUnit and get a red bar.🙂

    2) Result:

    public String resolve(String pattern, String input) {
    return pattern.replaceAll(“\\(1\\)”, input);
    }

    Somehow I think your test(s) might need to more fully define what you want the resolve method to do…

  2. You know what? I haven’t really done much intentional programming with Eclipse. I just assume that it matches Idea for most functionality. I left a step out here, however. Using intentional programming we should have returned to the test case after stubbing the class and found that yes it still does not compile. We would then want to use the IDE’s intention feature to stub the method definition, which should then allow the test to compile. I’m sure that Eclipse supports method stubbing as well as Idea. I confess that I use Idea regularly and have grown accustomed to the hot-keys for intentional programming. Under Idea, after stubbing anything (class, method, getter, setter) I always use the Ctrl+Shift+Backspace key combo to take me back to the last spot I was editing. (I’m pretty sure Eclipse supports that feature too under a different hot key sequence.) So the entire series of steps works as follows. Write a test against a non-existant interface calling non-existant methods. Finsh writing the test (reviewing to make sure it clearly expresses your intended use of the non-existant interface). Hit F2 (or the Eclipse equivalent) to step through the errors in the TestCase class definitions. (This should step you through each undefined object declaration, method call, and each undefined variable.) Use your intention key (Alt+Enter in Idea or Ctrl+1 in Eclipse) to get the IDE to fix the errors by stubbing classes and methods and adding types to variables. After any “fix” that takes you to another file or section in the current file use the “return-to-last-edit” hot key (Idea is Ctrl+Shift+Backspace) so you can stay focused on the task at hand which is to make the class definition compilable. After all of the stubbing and error fixing compile and expect a red bar. Come to think of it, that’s a pretty detailed list of steps! I should have been a lot more specific.

    Actually that was really the point of the above excercise. (That and the other point of shoving my work off to charitable kind hearted developers!) The idea is to introduce people to intentional programming and the warm fuzzy feeling you can get from it. If you missed any of my revised and more detailed steps then you’ve missed out on that warm fuzzy feeling. I’ll have to post another similar example in the future which more clearly expresses the big idea.

    Regarding a more formal definition of what I intend the resolve method to do:
    I expected something as simple as what you posted, Stephen. That became obvious as soon as I posted the topic. That’s the beauty of the approach. I can “get away” with some really simple code and enhance it as I go along while the IDE writes all of the boring code for me. Then again, I don’t know if that’ll fly too far in my particular case. What I’m really looking for is a way to pass a regex pattern that has something like a backreference and have the string substituted for the reference. Part of my problem is not knowing enough about regex so I know that my desires are still unclear. I know that you can use back references to substitute strings in a pattern. Although, it seems you also need to include a target string where the replacement will be performed. See I don’t want to perform a replace on a hard coded literal, I want something that’s more durable. I want a pattern language with replaceable tokens but I don’t want to break out into a whole new language with custom parsing. I was thinking regex could fill that void but I’m not quite sure.

    …Oh and thanx for the feedback Stephen!

  3. Either I’m misunderstanding the point of your post, you need to RTFM, or you’re trying (successfully) to give Java developers a bad name.

    You don’t need regex for this:

    java.text.MessageFormat.format(“com.mycompany.processors.{0}Processor”, new Object[] {“MyCustom”})
    returns “com.mycompany.processors.MyCustomProcessor”

    Now if for some reason you need to use ( instead of { or want to 1-index (as opposed to 0-index) your expressions, then you probably need to write some regex replace logic.

  4. You’re not misunderstanding the point. I don’t need the FM. I’m trying to give Java developers a bad name! You hit the nail on the head. Manuals are for sissys! Being a Java developer means you can use sheer brute force and throw as much technology at a problem until it gives! If regex didn’t work out I was planning on using an EJB approach involving syncronized JMS messages with XML marshalling to an XSLT transform. Get this. The interface would be a POJI marshalled by Spring over HTTP to a remote stateful session bean where the XML encoded message would be deserialized and sent over a blocked JMS call to a bean which would use a stylesheet to transform the actual text and plug in the variable. The result would then be returned back thourhg the JMS, satisfying the blocked caller who would then reserialize the message and return it back through RMI where the Springframework would then intercept and return to the original HTTP caller! I damn you for pointing out the obvious simpler solution thus thwarting my attempt at world domination, Duh!

  5. Cliff, whatever you’re drinking… I’ll have the water.

    But I’m on your side trying to give Java developers (at least the ones addicted to their IDEs) a bad rep. What programming community would miss several reviews on a class called AppilcationData?

  6. Tiago,

    Drinking? Nah cuz… my stoopidity is all natural!😉 Is there a class called ApplicationData? Who reviewed it? Man, not only am I insulting my favorite community, I’m horribly out of touch with the material that I misuse.

  7. Well, it wasn’t out there, it was once at work. I couldn’t remember the name of the class, but it was just as meaningless as “application data”. But since everybody used autocompletion, it took them a while to find out that the class was misspelled. Something like AppilcationData.

    I have also seen a “Mananger” interface once.

  8. Ok, I’ll put the whiskey down! I got’cha now. I’ve had some misspelled classes creeping around too. As a matter of fact I think I just put some in recently. You know that feeling you get when an interface looks misspelled but you’re unsure and it already has a bunch of classes compiled against it and it looks close enough and you’re too lazy to grab the dictionary even as it sits in your taskbar a mere mouse click away so you play it off and formulate excuses for the misspelling in case one of your buddies bring it back to your attention like “Dude, it’s ‘MethodReflector‘ not ‘MethodReflecter‘!” all while you have a snappy comeback like “I copied it from one of your corny concrete classes called ‘ReflecterHelper’ and refactored it!” so you still feel moderately superior even though you have that sinking feeling that it somehow points out that you never paid attention in Mrs. Hill’s fourth period spelling and cheated your way through high school but that’s all in the past so you hit the “submit changelist” button and just hope for the best. You know that feeling? Been there done that…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s