Java development with an iPhone touch pad for the Atari 2600 from an urban hip-hop perspective

Behavior Driven Development (BDD)

The bulk of my frustration lately is dealing with the concept of early optimizations that make sense. The idea came up in a recent discussion and I feel I should have challenged it. Once again, I’m developing for a very unique type of hardware that does require tight code, so there’s some unfamiliarity and apprehension involved. Still I wrestle internally with what seems to me like the wrong approach. In practice, any practice, are there any optimizations that make sense early on and don’t bite you after an iteration or two? I’ve run across a couple so far and I’m trying hard to bite my tongue. I guess what I really struggle with is the unfamiliarity I have with the platform as well as the unfamiliarity others have with the agile approach. It’s supposed to be about incremental improvement. That is you lay out the req’s in test form (or as a GSpec, wink, wink) spill out the first ugly solution (which in my case happens to be a shameless copy of existing code), and iteratively improve the implementation as well as the test. There is no getting it right the first time, or big round of cleanup and optimization at a later date. It’s all done at once, the interfaces being key.

I just got a green bar on a very tough piece of logic and I’m not satisfied with the implementation. I was driven down certain paths because of sensible optimizations. I now have the unfortunate task of undoing at least one of these sensible optimizations and explaining my changes. The project is very young so it’s not too big of a pain. The technology is new so I still stand the chance of being horribly wrong. However, my practice and my experience is yelling quite the contrary. That’s enough yapping from me. Time to refactor.

So I’m doing this embedded development right? And now I work with a bunch of guys that don’t obsess over pretty code, organized packages and outside in development, and easy build systems like I do. Things like public access members (and public access television) are considered the norm while method body size takes a back seat. I’m ok with some of the concerns: smaller memory means don’t spin up a bunch of object, use arrays over collections, change your underwear before going to bed, all seem like good ideas. What I struggle with (and will probably fight to the death over) is early optimization. I don’t care what device or platform you deploy to, optimizing before green barring is bad. You think you’ll save bits here and bytes there and you might be right. Maybe there’s redundancy between two method signatures and it’s highly likely. However, until you get that green bar you should leave all of the seemingly bloated and unnecessary scaffolding in place. Let your tests do the refactoring. Let your iterative design process shake out the redundancies. Small rant for now. Much more to come. If you’ve ever been in a situation where optimizing before getting a green bar saved your job (or rescued your cat) I’d love to hear from you. Include your life altering story in the square below, inquiring minds wanna know…

There’s alot wrong with it. But I wanna talk about the first obvious thing that jumps out at me, the type declaration. By the way, hi I’m Cliff and you’re here because the hairs on your chin look similar to the picture to the right. (…and that means either your Gillette no longer works or you have a higher than average aptitude for solving complicated problems and applying sophisticated algorithms to computer processes which results in more heat emitted from your skull which causes resident follicles to migrate southward where climates are generally cooler.) Chances are you know enough about Java or O-O to know what a concrete type declaration is versus an interface type declaration. However, do you regularly make a habit of declaring most of your variables as an interface type? Also are you aware of how important interfaces are for quality software? Do you know when it’s appropriate to use or declare a concrete?

Do you?
This is the part where I climb atop a soap box and babble for a while about something that struck a chord with me while I perform my daily programming tasks. Truth be told, I’m no expert on any subject and much of what you read here should be taken with a grain of salt. (followed by a fifth of gin chased by a 22oz bottle of beer.) But, BUT I tell you, what I have to say today could change your life. It could cause you to yield to others in traffic, tithe at your local church, and/or reduce your overall cholesterol intake by a certain magnitude. What I have to say today is relative. It’s religious as much as it’s good practice. I’ll begin with the moral and then fill in the details, “unless you’re absolutely positively at the mercy of a terrorist weilding a weapon of mass destruction or on a downward spiraling plane headed for certain disaster, use an interface.”

Why is it such a big deal to some people to use interfaces? Why is it such a big deal to others to avoid an interface? Those who are new to Java or OO as well as many who have used it for a while miss the concept behind interfaces. These people view interfaces as obstructive nuisances that impede a fluent development cycle. These are also the same people who have not gotten full use out of the tools available in their IDE many which include refactoring shortcuts and hotkeys. Then there are others who are reading right now and feel like I’m scratching that itch imposed by a fellow co-worker of the former type. These people know exactly where I’m heading with the text I fill this page with. These people have been in the game for a while and have actually been able to use the code they’ve written three months ago for a completely unfathomable purpose. These people come in all different shapes and sizes but typically resemble the picture above. These are my homies. (Honestly I don’t believe in stereotypes and most programmers (at least nowadays) don’t wear long beards or pocket protectors. We’ve actually evolved into a more handsome species capable of being cool and bugging out. Check out my mug shot above, that should show you how how attractive we’ve become.)

Enough Dumb Talk! Get To The Point!
I gathered you here today from far and distant regions of our planet to inform you (or in many cases remind you) what interfaces can buy. In the simplest case you have the ease of refactoring. Here’s a breif example of what you can expect:

Compile error!!! (Or if you live in the 21st century, editor squiggly line indicators around the 1st assignment in the method.) But that’s too easy right? C’mon nobody would change just the right hand of the assignment and try to compile. The more likely situation is:

See? No type incompatibility drama. Everything is nice and neat and you can shove those interfaces to Hell because they do nothing! But missing the point is what this article is all about. You see I did something clever in the code that we glossed over. I added stuff to the map. Now lets say that it is a lot of work coming up with the stuff we put into the map, I’m thinking several lines riddled with JDBC and/or XML. Let’s also make the situation more realistic by pretending the need for a sorted map came after an initial dozen rounds refactoring of the “add some stuff” code. By this time “add some stuff” has been moved into another method and finally into a set of delegate objects that each remember the Map’s origin. These delegates say stuff like, “I grew up with that HasMap back in 03′ when we had some crazy wild times smoking prepared statements, convertin’ BigDecimals, and catching SQLExceptions!” in other words they have methods that look like this:public void backflipWithDB2ComplexityAndLoadMap(HashMap map, ResultSet someunneccessaryParamDueToPoorDesign) {}
And there’s a couple of them. Furthermore each helper object got a record deal and blew up like MC Hammer getting calls from all over the place. Now lets try to introduce our TreeMap! See where I’m going with this? If not just imagine a huge collection of method calls all asking for and/or returning HashMaps. Now imagine cherry-picking these method calls one at a time trying to change the parameter and return types to TreeMap. Then imagine trying to go back and use a map from a 3rd party API after you painfully make the first global change.

How does this happen? Well because we didn’t use the Map interface to declare our variable we automatically “told” every one who uses the variable all of its dirty secrets. It’s the equivalent of passing the variable around naked. As we moved the code around and refactored we end up propagating the concrete type to parameters lists and return types. Had we used the Map interface instead (putting clothes on our variable) we could then use an old thing that works like a Map without touching any additional code. It just makes sense to use an interface.

Even when you use interfaces they don’t help unless you use them for most of your types. To explain I’ll give a recent example of what I ran into:

The above signature was found heavily used through the system by our only implementation that spoke JDBC to a database in a lower level. When we saw the need to introduce a new implementation that used record streaming or data pipelining from the DB the natural thing to do was write a List implementation that was actually connected to or delegated calls to an internal JDBC ResultSet. (I’m sorry, that’s too many syllable crammed together. Let me simply state it as we tried to turn a ResultSet into a List and return it.) We were stuck with about 475,373,595,698 touch points of impossible to test code in need of refactoring just to introduce our change. Had the original (idiot) author (me) of the method only declared a return type to be the List interface instead of the more concrete (like my head) ArrayList type the change could have been quietly slipped underneath all 475,373,595,698 touch points avoiding the horrible never dying zombie Find/Replace dialog introduced in a more recent version of Idea. (That’s a whole ‘nother story that I’ll rap to you about in the future!)

What else can I use interfaces for?
You can use an interface when you want to work in parallel with another developer. The interface becomes the contract between you two. You would have a conversation like:

You: Why don’t we build the Inventory Receiving software together. You do the UI while I work on the backend.
Him: That’s great since I love playing with Swing! How should it work?
You: We can start by giving the warehouse a screen to enter pallets numbers on. Then when the number is entered a full list of expected products and quantities should show.
Him: Perfect, I’ll give you a pallet number as an “int” and you can return a list of product objects. It can look like this:
public interface Receiver {
List receivePallet(int number);
}
You: I’ll get to work right away! I got everything I need.
Him: Me too!

Then at the conclusion when your bars are green and product management has signed off on his UI the pieces can be glued together with little worries of compatibility because you both worked off of a common interface.Also you avoid the need to step on each others toes; you writing or accepting Swing components and him assembling JDBC statements. Life is good.

Another good use for interfaces is (and most important) in unit tests. In fact I found that if you write your unit test against a concrete object then you’ve written throw-away code, both in the unit test and in the concrete implementation. All unit tests should start with an interface. They should also no nothng about how the implementation comes into existance if at all possible. I started writing my unit tests as abstract classes and I found that helps keep me focused on how the object is used instead of how it is written. In all cases you should not write any code until you have a firm design. Guessing at the design fools you into thinking you have the right design, but if you’re not using your design before you’ve written it then is the wrong designe in most cases. Writing a unit test is your opportunity to use your code before you write it. It sounds and feels awkward initially but it becomes addictive once you do it a few times. Also you should pay attention to the “intentions” or “quick fixes” features in both Idea and Eclipse respectively. Combined with a properly written unit test they are a way of getting your IDE to write 80% of your implementation for you keeping you even more focused on how the object is used from the outside.

So in summary interfaces let you:

Refactor without problems

switch the implementation with little if any touch points

work in parallel with another

focus on how your objects are used instead of how they are written

That said when in doubt, use an interface. This message was brought to you by…

Juxy the XSLT unit testing, poly-urathene based paint thinning, magic creme facial hair removing, anti-theft adulterous spouse catching product. Get your copy in stores today!
…and also by…Maven2 why maintain your build system when someone else can do it for you?
…brought to you in part by…Rory because the world needed another short, opinionated, big nosed, and drug free man of somewhat French descent….
…and also by…Groovy, the agile dynamic language for the VM that will make you feel retarded for buying that Ruby/Rails book on Amazon. I mean, honestly, who wants to learn yet another language, API stack, deployment solution, and methodology just to write DSLs and use closures when you have all of those goodies and more linked right into the JVM?

Searchmash lists me number one for the “best bdd java behavior”. I’m humbled but modest. C’mon, my product isn’t even finished yet! While it works on simple Groovy designs, It’s still mostly concept. Nice to feel important though. Let’s see what Google says…

I got rid of the nasty JUnitGSpecSuiteBuilder bug that was preventing my testSpec method from being executed. If you don’t know what any of that means just pretend that you do and be glad. I’m now working on using Groovy M.O.P. to add GSpec’s dynamic methods and properties instead of using the wrapper object. What that means is pretty soon GSpec will be ready for use on typical Java projects. A little more work is necessary to plug it into JUnit but I’ll smooth that out in due time. For now, if anybody knows how to work around IntelliJ Idea’s desire to clean up your compiled Java classes when you compile a groovy class with GroovyJ drop me a line. Wait a sec…! I just got something happening using the Maven2 compiler instead. I gotta get my development environment in better shape!

I found an article that preaches a technique that I’ve recently adopted. That technique, I guess, can be formerly referred to as design by contract. (Keep this page bookmarked because I’m thinking of posting a brief example over this weekend.) In short, what I do is start my unit tests using abstract classes. Abstract classes?? Get the Hell outta here, right? Those went out of style with high-top Pro-Keds didn’t they? Well as it turns out there are a few good uses for them, one being unit testing. How does it work? I’m glad you asked! Let me explain…

Abstract Test Driven Development
When I begin a unit test I start with the word “abstract” (actually I start with the word package, followed by a package name followed by several import statements but since I use an IDE I don’t write that part so I start with “abstract” as I was saying…) And I include an abstract method, “getInstance”. I then make “getInstance” return some named type that doesn’t exist. That’s the fun part because I can be as clever as I want and even change the name half into my design without hassle. I then pound out all of my test (*ahem* spec) code into these neat little method bodies that are free from the clutter of implementation details. That’s where it becomes even more fun because I can be as creative as I want defining the behavior of my test object, changing names as I need without trouble. The test methods focus on how the object is used and they actually write the interface for me. When I’m done, IntelliJ Idea fills my screen with all of these little red squiggly lines under each undefined type and reference and I merrily go through with my F2 key and correct each one. (F2 steps between file errors, Alt+Enter fixes each error generating interfaces and methods with simple key strokes. You gotta try this, it’s loads of fun!) I stub out my interface, then (using Ctrl+Shift+Backspace) I quickly return to my test and resolve each undefined method or reference. What I’m left with is an abstract class and an interface which together do nothing but in reality do everything. They define the contract. The test writes the contract. The interface is the contract.

The next step is to place my cursor on the test class name and hit Alt+Enter. (In Eclipse you substitute Ctrl+1 for Alt+Enter and get the same magic.) What does my editor ask me? “Hello Cliff, my it’s a sunny day today! Would you like me to generate an implementation of your beautiful abstract unit test case for you? By the way I’ve also noticed that your chair is slightly unleveled. Would you care if I adjusted that fold of rug tucked underneath the wheel?” So my actual test case is written for me while my seating is adjusted. (Man, I love Idea! Eclipse, unfortunately doesn’t have the seat leveling plug-in yet.) I am then placed inside my actual unit test at the point where I am supposed to dream up a clever name for the actual object that I’m going to test. I haven’t created it yet so, once again, I can be as imaginative as I need to be. I prefix my object name with “new ” and suffix it with parenthesis “()” which may or may not include its dreamed up dependencies. My editor is smart enough to understand that I want to create the tested object at this point so it generates the concrete walks me through. (The constructor and any additional interfaces methods can be generated by chasing the light bulb and using Alt+Enter.) I return in a flash to my last place of editing. (I was working in the concrete unit test before I started writing the concrete implementation. I use the same Ctrl+Shift+Backspace to walk back there.) I tell my editor to run my unit test (in Idea a right click on the test class name will add an option to run the unit test to your context menu. Idea is also smart enough to run the compiler over everything first.) an wait for my red bar.

We love the red bar don’t we?
Here’s an important detail that is often overlooked by many when practicing TDD. The red bar is just as important as the green bar because sometimes a test can pass before you’ve written a line of implementation logic. Initially a green bar usually means your unit test is either broken or unnecessary. After the red bar I play fill-in-the-implementation-blanks using Ctrl+Alt+B to step into the implementation of a method from the calls in my base test case. It feels and looks much better than it sounds so I’ll come back later with an actual example so you can see what I’ve been yapping about in my other article.

What is BDD? Webster defines it as Behaviour Driven Development. (Not that Webster, this Webster! Yeah, I asked him the other day and he was all like, “Behaviour Driven” in his tiny voice.) I stumbled across the idea a while ago thanks to the lovely folks over in the Ruby camp. They have taken the idea of Test Driven Development (know as T.D.D. for those of you who have A.D.D.) to the next level giving us a tool called RSpec. While the tool is fascinating the idea behind it is even more intriguing. (By the way, I’m not giving or taking all credit to/from the Ruby camp because I’m not sure who fathered the idea. I mention them because they were the first ones that introduced me to the concept. But as concepts go everyone want their name mentioned so I’ll just pretend for the sake of discussion that I made the entire idea up all by myself with no help or insight from Ruby or anyone else whatsoever!) BDD focuses on the ideas central in Neuro-linguistic programming (NLP). If you read from that link you be pummeled with long-head words like axioms and adherents as well as a bunch of theory on psychology. The idea is simple. The words we choose affect how people think about things. That’s essential because the way we think about things effects how we do things. How we do things effects things that are done to us. Things that are done to use effects… well I’m off topic and I’ve probably oversimplified and confused everybody. Let’s try an example of the idea.

If your spouse told you to, “take the garbage out front!” You would likely receive that as a direct order or a challenge. Some people may take it as a threat. “Take the garbage out or else what?”, is the thinking. However, if your spouse informed you that, “the garbage needs to go out for trash night” you would likely be more receptive. Another example would be “Move from in front of the T.V.!” once again words that are likely to be perceived as threatening. However, “I’ll take the garbage out as soon as I can see who’s winning the game.” could result in a much more complimentary reaction from a spouse. (Not in all cases and I should tread lightly because in in dangerous and uncharted territory with our discussion here.)

What does trash and Football have to do with programming?
Most football fans talk trash when they write code. (Does that tie it together well enough?) The truth is that code is made up of words. A popular observation is that code is primarily used for/by people, a fact that is easily forgotten in the industry. When you use the right words you convey your intentions clearly which allows people to understand and respond accordingly. That leads to increased productivity resulting in happier times for all involved. When you choose the wrong words your intentions are lost which result in people following the wrong direction and creating their own paths. You code should convey intention clearly focusing heavily on the what and why of a process rather than the how. Those intentions should match the intentions of the user of that code. The intentions refer to the desired behavior. The net affect is that choosing the right words to describe the intentions results in proper behavior (you desire your spouse to behave by moving out of the view of the TV, choose your words correctly). In short, you achieve the intended behavior best by choosing the right words. Because humans do not respond well to direct instruction (think how you might not respond to, “take the garbage out front”) it makes the most sense to write programming logic in a way that it reads less like instruction and more like a story. Starting from TDD you understand that the test is written first. Since the test is also programming code it too should read like a well written description of intended behavior. That is the big idea behind BDD.

Fluent Interfaces
One of those high octane words describing pretty programming logic, fluent interfaces is a term coined by Martin Fowler. It is a means of making your source code easy to ingest, heavy on intention and low on calories. I take advice from him and others such as Kathy Sierra who taught us the importance of coding like a girl. I’ve taken a stab at writing fluent interfaces in the past and later learned that practicality sometimes becomes more important than pretty design. However, fluent interfaces, girlie coding habits, and just plain self documenting method signatures add way more value than they remove. Adopting these practices when writing tests will make those tests read more like specifications of intended behavior. GSpec is born as a test framework that operates as a specification framework which blesses your code with such fluent interfaces at runtime. I don’t even like using the word tests because it is the wrong word to describe what we actually should be doing when we follow TDD or BDD. I prefer the word “specification” and would rather refer to the process as Specification Driven Development or SDD. (Only that sound too much like STD which could distract from the overall benefits of the practice.) Remember, in theory, choosing the right words more likely results in the intended behavior.

Enough theory, lets get to some examples
Programming is all about making dough right? So let’s make some bread! I’ll walk through a fictitious example of making toast TDD style then we’ll see what BDD adds to the design. Let’s pretend we want to make toast with TDD. Yes, most people use a standard toaster for this purpose but it isn’t as much fun as writing our own bread from scratch isn’t it? We start with an empty test and an interface which doesn’t exist yet. (TDD when done properly uses your imagination to pretend your interfaces exist.):

publicclassBreadTest extends TestCase {
Bread bread;
}

Then we add our tests. I’m thinking that we would set the temperature of our bread to 325 degrees before it turns into toast, though I have no idea if that’s actually right in the real world. (My wife is the true cook of the family.)

That gives us our interface that my IDE (that’s an Integrated Development Environment or a tool to write computer programs for my not so tech readers who are bold enough to try to understand what I do after work.) happily generates for me here:

Not bad for a slice of wheat but we weren’t as concerned with behaviour as we could have been. To show you what I mean let’s consider making toast with GSpec BDD style. (Editorial note: GSpec can also be used for other random household tasks such as thinning paint, polishing tile, or greasing the pan prior to baking.) I leap into action with the following spec:

Without cheating I go to the beginning. I start from an empty Bread interface and an Empty Class definition of our WheatSlice. Running against it gives me the following failure:

A slice of bread
Adding enough heat to a slice should turn it golden brown and crispy.
Caught: groovy.lang.MissingMethodException: No signature of method: com.craig.sandbox.WheatSlice.addHeat() is applicable for argument types: (java.lang.Integer) values: {100}

Now I’m like, “Hey GSpec just pointed out a design flaw! I should blog about it!” Actually, to GSpec’s discredit, it didn’t do anything but complain about a missing method. (It’s far too alpha to suggest good practices. I’ll be adding such advanced AI in my 2.0 beta release.) Best practice lead us to the conclusion that we needed bread bread to allow us to add heat. The difference is subtle but important. Using more English like grammar made me feel as if I should be adding heat instead of setting a member variable as I did before. You see, when writing a TestCase it is easy to focus on testing because you’re writing a test. Also because many/most of your methods begin with the word “test” by convention. When the word test is used repeatedly it becomes natural to think of implementation rather than behaviour. Enough babbling, let’s get onto the rest of our design. I now start filling in the blanks of my design with implementation. (Notice how adding logic is referred to as filling in the blanks of the design.)

Now after running I get this:A slice of bread
Adding enough heat to a slice should turn it golden brown and crispy.
Caught: groovy.lang.MissingPropertyException: No such property: cooked for class: com.craig.sandbox.WheatSlice

Now I start understanding what a slice of bread is supposed to do for me. It’s supposed to allow me to add heat and show me whether it’s cooked or not. I’m focused more on behaviour of adding heat and cooking a slice than I am with setting and examining individual properties. (I understand this is a really contrived example and the design can be argued but bear with me. I’m pretending to know what I’m talking about for the sake of explaining GSpec.) I add [ boolean isCooked(); ] to my Bread interface and generate the following in my WheatSlice class to get to the next step:

We ask the simple question, Why is our Bread not cooking? The answer is simple. We haven’t done anything with the heat that we’ve been adding. I’ll combine a few iterations to save space on the page and jump into the final code that satisfies the Spec.

Running the above through GSpec gives me:A slice of bread
Adding enough heat to a slice should turn it golden brown and crispy.

Process finished with exit code 0

Before I get hate mail from every TDD advocate complaining about how I did away with the green bar let me explain. JUnit support is still flaky and incomplete. I’ve been also struggling with Maven2 support on the build as I eventually plan to get the entire thing roped into surefire somehow. (I may have to write my own Groovy M2 plugin using Jason’s framework which would be fun.) Greenbars and JUnit aside, it’s the concept that’s really important. What we now have is a slice of bread we can put into a toaster and it should behave accordingly. (Maybe we can design a toaster in a future post.) In conclusion, Behaviour Driven Development (BDD) is what Test Driven Development is supposed to be all about. Whether you use GSpec (which is still very Alpha) or JUnit or TestNG or something else, your design should elevate the importance of how each object or component is used. Implementation should be a matter of filling in the blanks of a well thought out interface with minor bits of functionality. That’s that good stuff there! Ya’ with me? If ya’ feelin’ the same, fill in your name, drop me a comment y’all know the game…

GSpec is a registered trademark of Craig Conglomerates. Any unauthorized use of the name is subject to heavy financial penalties in excess of $250 million. Unauthorized users will also be subject to 495,672,395 repeat airings of alternating back to back episodes of both Mama’s Family and The Golden Girls. A fair use license may be granted upon submitting your name SSN and bank account info to Emporer Craig and subsequently applying for entry into the Hall Of Aim.All other restrictions apply, tax title and tags due on inception. Contact your local dealer for details.