Showing posts with label craftsmanship. Show all posts
Showing posts with label craftsmanship. Show all posts

Friday, October 24, 2014

A TDD story about a test that started "green"

This is a story is about the value of making sure you start with a test that's actually failing.

First a little context. I've been sharpening my TDD-fu and design-fu with a pet project: implementing the rules for Monopoly, the venerable and venerated game from Parker Brothers. (For some interesting background reading, check out the original rules and the Wiki page describing Monopoly's history.) The game's domain model and rules are fairly rich, making this exercise reasonably challenging and thought-provoking; and the rules are well defined, so the stories are easy to find and are clearly constrained. (There's little chance of me going off the rails chasing an interesting subset of the problem domain.)

Someday, ambition and time permitting, I might write a whole series of posts on this. Today I'm going to describe a particular situation and how it highlights for me the value of starting with a "red bar" when a new test is written.

This story begins with a new test named shouldNotAllowTurnsWhenGameIsOver. Its intent is to ensure that the winning player can't continue to take turns when game is over. There is a winner when all but one player is bankrupt.

I already had a test that ensured bankrupt players couldn't take a turn, and another that verified a winner was identified when all other players were bankrupt. But I didn't have any specific logic in the game implementation to ensure that the winning player couldn't take a turn after the game was over. So I was a little surprised when I ran my new test and it passed.


When I write a test I'm saying "I want this to happen when I do that". When I run that new test and it tells me I'm already getting this to happen before I've written any production code, there's something wrong.

A test that starts out green is a bad sign: first, you don't know that it can ever be red, and thus it can't be trusted to do anything useful. But equally importantly, it's a signal that either something in the production code is accidentally resulting in the test passing or the test is not valuable and ought to be scrapped or rewritten.

My initial thought was to rewrite the test to make it go red, but I couldn't figure out a way to change it that didn't rely on implementation details. So I dug into the code.

A little investigation revealed the answer. In the GameState class I keep track of which player will take a turn next in an integer field named nextPlayer. The GameState#getNextState() method figures out what the next state is when a turn is taken, and constructs an instance of the correct type:

       GameState getNextState() {
           if (game.hasWinner()) {
               return new GameOverGameState();
           }
           return new TakingTurnsGameState(nextPlayer);
       }

Notice the difference in the constructor calls to GameOverGameState and TakingTurnsGameState. The GameOverGameState constructor doesn't have a nextPlayer parameter, so its nextPlayer field is initialized to 0.

I fixed this by refactoring to always call the GameState constructor that takes a nextPlayer parameter. Once I did this, the test turned red and I could continue normally, implementing the code to make it green.

I also wanted to dig a little deeper. After a little root cause analysis (walking backwards through my commits) I decided I had made two mistakes earlier. The first was implementing code in a way that required me to know about (or assume) a future requirement. (I knew that once the game was over no more turns would be taken, so I assumed the value of nextPlayer didn't matter when creating GameOverGameState.) The second error was not ensuring that all fields of the GameState class were properly initialized on construction. (Don't leave your fields uninitialized, kids!)

Following a good TDD process helps find defects early and leads to a better design by making it safe and easy to refactor code. But it is very much not an automatic process. You have to pay attention and be diligent and conscientious. I was able to find and fix a bit of troublesome code today by paying attention when a new test was passing.


tl;dr, if you get a green bar first when writing a test, pay attention: there might be something smelly in your code.

Sunday, January 27, 2013

Correctness, Clarity, and Changeability

I have a strong personal drive is improve my productivity as a software developer. Consequently I do a fair bit of reading and thinking about how individuals and teams create good software. Since this is a baby blog I figure it might be a good idea to start by exploring some of my ideas about what "good software" looks like.

Like any other human endeavor, software development is kind of messy. We don't communicate well; we make mistakes every day; we are horrible at predicting the future; we make irrational and imperfect decisions. But we still manage to succeed, and occasionally we succeed brilliantly. Developers who are the most effective -- who succeed brilliantly -- have learned how to become really good at creating good software.

So what does good software look like, from the perspective of a software developer? There are a lot of "right" answers to this. One that I've come up with and like is in the title of this post, and yes, I came up with those three words because I like alliteration. Good software has the attributes of correctness, clarity, and changeability.

Correctness means satisfying the needs of the customer. If it doesn't do what the customer wants and needs, it isn't correct. In development-speak, this means the software satisfies the functional and non-functional requirements. Functional requirements are the 'what' of the software; the features I can use. Non-functional requirements are 'qualities' of the software; things like security and performance and robustness and availability and usability. Correctness is subjective, which is why there is often a lot of (sometimes heated) discussion among stakeholders about whether some program ought to have fewer bugs, or have more features, or be more usable, or be more responsive.

Clarity means the code, build scripts, shell scripts, database queries and scripts, internal documentation, configuration files, and other bits necessary to create a piece of software are as easy to understand as possible. The source should be self-documenting and well-organized, so that its behavior and purpose are obvious. Self-documenting code is obvious in its intent. It's characterized by meaningful names; by constants instead of magic numbers. Self-documenting code makes it easy to answer the question, "What does this code do?" Well-organized code makes it easy to answer the question, "Where is the code that ...?" The package (namespace) structure is clear; classes in each package are closely associated; structural and behavioral associations and dependencies are easy to find. The overall project structure makes it easy to find all of the code, scripts, configuration files, etc. that need to be changed in order to implement a feature.

Changeable means that the software is as easy to change as possible. Implementing new features and refactoring to support new requirements should require a minimum of effort. Good design and a solid test suite go hand in hand with changeable software. Good design makes it easy to make changes and still have the system compile. A good test suite makes it easy to make changes and still have the program work correctly. Use good design principles like DRY and GRASP and SOLID, and write good unit tests, and you'll have code that is easier to modify.

So how do we create software that is correct, clear, and changeable? The best answer I have found is in the principles of agile development. Agile development allows a team to be effective and productive over time. Or to put it another way, agile methods lead to software that is correct, clear, and changeable.


Friday, October 19, 2012

Sources of Technical Debt and Bad Design

As a software 'craftsman' I appreciate the intrinsic beauty of good design. And I have an internal, almost instinctive, dislike of poor design. It's like seeing graffiti on the wall of a church or listening to someone sing out of key. This alone is enough to make me want to write good code, and fix bad code. But design is about much more than aesthetics. It takes a lot less time and effort (costs less) to add features to a project that has a good design. And that's good for everyone -- developers, management, and users.

(By the way, when I say "design" I mean the entire application. Not just the Java or C# code, but also the build environment/tools, database scripts, shell scripts, etc.)

So why do so many projects end up with a horrible design and a mountain of technical debt?

No team sets out to create a poor design. But many (perhaps most) projects end up being difficult to understand and modify. Some eventually end up with so much technical debt that the team or management decide it's better to start from scratch. (Which is often another sort of mistake.)

So where does bad design and tech debt come from? Here are some causes I'm familiar with:
  • Time constraints. In the midst of getting an application to build and work right, we often take shortcuts. Another name for 'shortcut' is 'technical debt'. Technical debt is usually rationalized as being necessary to meet a deadline. Sadly, just about every excuse or justification we use to "save time" winds up costing us or our beloved colleagues much more time tomorrow as we saved today. Another way of saying "we don't have time to clean up the code" is "it's going to take twice as long to add a new feature in six months as it does today".
  • Personnel changes. New team members can be great contributors to bad design, by writing code that is incompatible with or breaks the existing design. Maybe because they don't understand it, maybe because they think they have a better idea (ego-driven programming), maybe because they're thrown into the fire without any help. "Okay Steve, your first assignment is to add history tracking to changes to the model so the user can revert commands. I'd work with you on it but don't really have time. You can stop by if you have a question, though."
  • New requirements. Sometimes a new requirement comes along which is incompatible with the existing design. The right way to handle this is to refactor the existing code towards a new design that fits both the existing features and the new one. The more common way to handle this is to "tack on" the new feature by hot-gluing it to the side of the existing code and slapping some paint on it.
  • Inexperience and ignorance. Whether it's a new technology we haven't used, a domain we're not familiar with, or a general lack of experience in development, not knowing the "right" way to get it done will almost certainly contribute to a bad design and/or technical debt.
  • Familiarity. Familiarity tends to create blind spots and acceptance of bad design and technical debt. You get used to dealing with the randomly failing unit tests, or the bizarre class hierarchy, or the 15 minute deployment cycle. And you forget that it's really pretty messed up and needs to be fixed.

Nobody prioritizes bad design or technical debt; it happens as a side effect of decisions we make every day. Sometimes it's an intentional decision, possibly made with an understanding of the consequences and with the best of intentions to go back and do the rework necessary to clean things up later. Sometimes the decision is made unconsciously or in ignorance of the consequences.

The only way I know of to prevent and eliminate technical debt is to be intentional about removing it when you see it. It's like housekeeping and home maintenance: you dust and vacuum and sweep, pick up and put away tools and movies and toys, and replace the old weatherproofing around the door. The most successful teams I've been part of are good at housekeeping: they have been disciplined about using best practices to keep technical debt at bay and maintain a good design. (And by the way, when I say "team" I mean everyone who is part of the project -- programmers, documentation, QA, UX, BA's, and management.)

So do your chores and keep the house clean. It's worth the effort.