ALT.NET Open Spaces - Registration Open!

Registration has opened for the ALT.NET Open Spaces Conference! The cat’s out of the bag, the gates are open, release the bats! We have a limit of 100 People so get while the getting’s good (looks like there’s ~33 openings at the time of this post). In the coming weeks we’ll be communicating with the people who are coming to Austin, sharing plans and pointers for the Open Space-ness, etc.

Agile Cheat Sheet

Sure you’ve got the ReSharper 3.0 cheat sheet taped to your monitor, but what do you have that’s reminding you of values and principles? You need an Agile cheat sheet!

Luckily I’ve got one for you right here! Print it out and put it in your team room, tack it to your task board, and tape it to your monitor.

I made this about a year ago and put it up on the bulletin in our team room. From time to time a stakeholder will wander in, notice it, and ask about it. Then I say, “well let me tell you about this, it’s really exciting.” 

It’s a handy information radiator for everyone and an omni-present reminder of how we, as Agilists, stay on point.

The Box Got Hotter

A great analogy for side-effects in your programs from Simon Peyton-Jones:

In the end any program must manipulate state. A program that has no side-effects whatsoever is is a kind of black box, right? You press go, and it runs, and all you can tell is the box got hotter.

Check out the video of his talk on Haskell at OSCON 2007 for this and many other gems.

Boring Inside

I’m burning down some podcast backlog as I wait (and wait and wait) for a plane that’s been delayed (and delayed and delayed) when I hit part of a Hanselminutes episode featuring Jeff Atwood on the topic of building your own PC. At one point, he observes that it’s kind of nice to know what’s going on under the hood of your workstation and that knowing something about the internals of your hardware can make you a better developer.

I couldn’t care less about hardware. I care about my experience — keyboard, mouse, video walls – but the internals — Intel, AMD, pico-hampsters running on pico-hampster-wheels – make absolutely no difference to me.

To me infrastructure is a dial tone. It needs to be there, respond to my request, and let me get to the stuff I care about with minimum hassle. I care about understanding a problem or opportunity and finding its most direct and elegant solution in software. Of course my workstation needs to be fast and usable. Of course it needs to be reliable. And, oh yeah, if it could look pretty, that’d be an extra bonus.

The developer uses tools to build tools. Software solutions, when delivered into the hands of the end user, are a tool. I build or acquire tools that help me build another tool. There’s a lot to figure out and grok. Throw in our industries frenetic rate of change and there’s plenty to keep me busy for several lifetimes.

Okay. That’s kind of a who’s on first way of saying the craft of developing software is generative: tools produce tools produce tools. Wouldn’t my time be better spent learning and mastering other elements of pure thought stuff? New languages, frameworks, patterns, techniques, and (you guessed it) tools?

I crave the form and trust the details. Knowledge of hardware internals might possibly inform your craft, but an examination of history, art, architecture, city planning, philosophy, or psychology might inform in a more creative, less pseudo-comparative way. 

And before I hit publish, some disclaimers:

  1. I would care about hardware if it were part of the problem domain I was making software, e.g. embedded systems, network monitoring, device drivers. As soon as I moved on, I’d stop caring.
  2. I am very thankful that there are people that do care about hardware. Good network design/engineering/support (for example) is its own craft with its own horizon!

Exercise and Expect Discipline

A few days back I was reminded of Shuhari. It’s a concept originating from Japanese martial arts that describes a three stage self-development process where a student progresses from novice to expert to master.

Perfection is a pervasive theme in the larger Agile community.  Scott Bellware makes an agreeable point saying we should focus on the verb, not the noun; Dave Nicolette has a pragmatic take on adoption of Agile methods; Alistair Cockburn brought the term Shuhari to the Agile vernacular.

I have in my mind’s eye a particular scene from The Last Samurai. At one point the camera pans over a rural village where the town’s folk are engaged in their various activities of daily living. Captain Algren observes:

From the moment they wake, they devote themselves to the perfection of whatever they pursue — I have never seen such discipline.

Is the action is the actor’s raison d’être? Yes, but there’s more to it than one person and their craft. There’s an interdependence between the villagers. The group dynamic creates an environment of healthy peer pressure that ingrains, supports, and reinforces the discipline required to pursue perfection. I depend on my neighbor, a potter, for my earthenware. My neighbor depends on me, a farmer, for my vegetables.

Committing to the Agile way is a decision to pursue perfection. Discipline is flat-out, straight-up, and without a doubt the most fundamental ingredient in advancing on the path. Everyone involved in an Agile project or organization needs to hold discipline up as a precondition to continuous improvement. Customers, developers, managers, executives… everyone. Improve your craft, exercise self-discipline, and expect your team to do the same.

How Many Licks?

Javier poses the question: “how many [CLR Objects] does it take to represent a Real World Object?” I have posted in about this in the past, but it’s an excellent question that throws a lot of folks. I also think I’ve refined my opinion on the question and it’s good to revisit these things every so often. The question made me think back to an old school commercial for Tootsie Pops that aired during Saturday morning cartoons:

image image image image image 

In the commercial a boy approaches an owl, Mr. Owl to you, with a question: “how many licks does it take to get to the center of a Tootsie Pop?” Ever the empiricist, Mr. Owl engages in a short experiment. Loosing his discipline after three licks the owl bites into the candy’s chewy, pseudo-chocolate inner core. The owl licked thrice before chewing. He asserts, therefore, it takes but three bites to get to the center. The boy seems dissatisfied with the conclusion of Mr. Owl’s investigation worriedly observing that ”the world may never know.”

The number of objects you need to represent a real world entity can vary greatly depending on the needs and architecture (which should be driven by the needs) of your application. I’m still a believer in one entity probably isn’t enough. Let’s introduce an example. Say we have to represent Customer somewhere in the application.

My first question is what makes up the Customer? Likely they’ll have one or two address objects? Let’s say they have two, a shipping address and an office address. So far we’re up to “thu-ree” - as Mr. Owl says - objects. Customer in this sense is a composite or, in DDD terms, an aggregate root. So right we’ve got (potentially) an effective infinite number of “objects”. Let’s make “object” mean “type” or “class” going forward. If we recast the question as “how many types does it take to represent a real world object” we can come up with a finite number of associations be they many-to-one, many-to-many (association class), or one-to-many (collections). Still I like the idea of “Customer as boundary” that comes with the DDD notion of aggregate root.

So how do we get that Customer to our application layer? Generally speaking I look for an organizing principle (information architecture) centered on the main entities of the application. I like to group screens and actions in the UI around the entity. So I’d like to come up with a screen that lets you act on a list of Customers or open an individual customers, browse its data and take action on that instance of customer. Even though there’s a certain nakedness to these business objects I tend to favor creating DTOs or messages that represent the required slice of data. For example, I’d consider a list-like DTO of Customers that’s contains data that helps you find an individual Customer represented by a more jagged, higher resolution detail DTO. I also don’t invest too much time in factoring my DTOs for re-use, so I’m apt to create a DTO specific to the purpose at hand. 

Sidebar: I use a base class and external DSL for data transfer objects and have them support data-binding. Read more about it. I know CSLA, for example, goes with a kind of single entity approach. Rocky calls it “mobile objects.” That is a customer is a customer is a customer. I don’t like this because I feel that it creates a lot of transformation code everywhere and I like to centralize this in a Service Layer. I also avoid loading my entity classes with responsibilities orthogonal to business logic such as data-binding support. Instead I favor a Service Layer peopled with Application Services. An Application Service is really a facade to the Model layer that brings infrastructure (sending an email) in to the mix with Domain artifacts: Entities, Repositories, Factories, and Services.

Now we’ve got all these messages that support a user interacting with the model of a “real world object” and we’ve got a number of MVP triads that ultimately construct these messages that work on the entity. I guess my answer is as many as it takes and it can take quite a few. The benefit of splitting a real world object into a number of tailor-made (for the layer) objects is that it preserves a layered architecture which benefits through partitioning and isolation. That’s a Byzantine way of saying layers make a code base easier to evolve/maintain.

If I had to break it down to for my current default architecture for smart clients that work over a firewall:

  1. Customer (Aggregate Root Entity)
  2. Address (Value Object)
  3. CustomerRepository (Finds/Saves/Deletes Customers)
  4. PreferredCustomerService (Gets a list of Orders for a Customer and determines if they’re standard, gold, or silver)
  5. CustomerService (CRUDdy Application Service for Customers)
  6. CustomerDetail MVP Triad
  7. CustomerSearch MVP Triad

All of these items are required to represent the real-world customer given my architecture. Even if you go directly to model you still need to display stuff. Even if you’re not using MVP and are using Autonomous View, it’s still another object required to “represent” the real-world concept of customer. My preference is simply to let the concept of “Business Entity” flow through a layered architecture when it’s natural to the end user. In general I think it is a natural concept for a lot of entities. Adjusters talk about working with claims; underwriters write, renew, and terminate policies; project managers manage, well, projects…

Having this baseline set of patterns helps you avoid the trap Mr. Owl fell in to. Namely, patterns control how many licks, um, objects it takes to get to the center of a user story and at the heart business value. You don’t need to go nuts with an over-arching, prescriptive framework. Pick a few design patterns to start with and a framework will emerge over time as you suit immediate needs, ease frequent pain points, and address redundancy. I, personally, look for how entities are treated, look to them (initially) for an organizing principle of user experience, and find design patterns that mesh my findings with a good measure of maintainability and testability.

One Logical Assertion Per Test

Having had the chance to get some good feedback from Aaron on my One Mock Per Test post I’m refining the TDD rules I’ll live by going forward.

I still believe tests should have a single assertion, but as Ayende points out occasionally a single call to Assert.ThisOrThat won’t cut it. What we really want to preserve a single logical assertion. Put another way, if a test has multiple assertions, each assertion must exhibit a high cohesion with the specification described by the test. In Ayende’s example each assertion has a shared mission: verify the contents of a row-like structure. The nature of the specification dictates more than one Assert. Without having to use too much imagination we can see in some circumstances it’d be overkill to check that each individual cell is set with a separate test, given that he’s working at the row level. I’ll pretend his specification says “a row is put in a certain state.”

An example test that uses multiple assertions in a highly cohesive manner:

[Test]
public void A_user_sees_results_of_a_gold_customer_search()
{
   ICustomerSearchService mockService
      = _mocks.DynamicMock<ISearchService>();

   ISearchView stubView
      = _mocks.Stub<ISearchView>();

   // puts 26 customer entries in a fake DTO
   CustomerSearchResultDTO fakeResults = GetFakeResults(26);

   using (_mocks.Record())
   {
       Expect
         .Call(mockService.FindCustomersByLevel(CustomerLevel.Gold))
         .Returns(fakeResults);
   }

   using (_mocks.Playback())
   {
      SearchPresenter presenter = new SearchPresenter(stubView, stubService);
      presenter.FindGoldCustomers();
      Assert.AreEqual(”Gold Customers: 26″, stubView.Title);
   }
}

In the example there are really three explicit, but highly cohesive, assertions in this contrived example:

  1. I expect that ISearchView.FindCustomersByLevel will be called
  2. ISearchView.FindCustomersByLevel will be given an enum argument CustomerLevel.Gold
  3. The view (technically a stub) will have the title “Gold Customers: 26″

In the real world I’d likely treat the stubView as a mock object and set an expectation that it’s Data property receives the fakeResults. Another thing I’d probably do is stick with all interaction testing and treat stubView as a real mock object. I’d set an expectation that Title was set instead of asserting Title was set to a specific value after the fact. To me it’s a clear case of six to one, half-a-dozen to another but I suppose there’s something to be said for not paradigm shifting too much between interaction/state testing if it can be avoided.

However you cut it, these are highly cohesive assertions; they belong together and describe a complete interaction. The test is still satisfyingly small so I continue the benefit of quick return to test mode after passing green.

As an aside: I like Aaron and Jacob’s advice about using DynamicMocks (when using Rhino Mocks) as a way of building a more flexible refactoring/change safety net from your tests.

One Mock Per Test

Update: I’ve slightly revised my viewpoint on this. Hooray for changing one’s mind!

At my last talk I casually threw out the idea that you should, generally speaking and as a rule of thumb, keep each test down to a single mock. I my mind this is similar to the one-assert-per-test guideline. Consider this code snippet (using Rhino Mocks) and let’s pretend it came about through a TDD session which, as we may or may not see later, may or may not matter:

[TestFixture]
   public class SearchPresenterTests
   {
      private MockRepository _mocks;

      [SetUp]
      public void Setup()
      {
         _mocks = new MockRepository();
      }

      [Test]
      public void Can_search_for_customers_by_number_of_orders()
      {
         ISearchView mockView = _mocks.CreateMock<ISearchView>();
         ISearchService mockService = _mocks.CreateMock<ISearchService>();

         SearchResultDTO fakeResults = new SearchResultDTO();

         using (_mocks.Record())
         {
            Expect
                  .Call(mockService.GetCustomersByOrderCount(42))
                  .Return(fakeResults);

            mockView.SearchResults = fakeResults;
         }

         using (_mocks.Playback())
         {
            SearchPresenter presenter =
                  new SearchPresenter(mockView, mockService);

            presenter.SearchByOrderCount(42);
         }
      }
   }

A user fills out a textbox with a parameter value, clicks a button who’s click event handler calls back to a “Search” method on our presenter giving it the parameter value. It’s a pretty standard scenario for MVP.

Well what’s wrong with this? At first blush nothing. It’s a fairly minimal. The problem is that word fairly. It’s a slippery slope friends and this test is getting a bit beefy for my tastes; I’m testing two behaviors. I’ve got two specifications here: 1) “A user can search for customers by order count” and 2) “Search results are displayed to the end user.” I took a pretty big step there.

Of course, I’m making this stuff up, but let’s go with it and make the tests and break the tests in twain (for the impatient reader, skip to the bottom where I get to the why):

      private MockRepository _mocks;
      private ISearchService _stubService;
      private ISearchView _stubView;
      private SearchResultDTO _fakeResults;

      [SetUp]
      public void Setup()
      {
         this._mocks = new MockRepository();
         this._fakeResults = new SearchResultDTO();
         this._stubView = _mocks.Stub<ISearchView>();
         this._stubService = this._mocks.Stub<ISearchService>();
      }

      [Test]
      public void Can_search_for_customers_by_number_of_orders()
      {
         ISearchService mockService = _mocks.CreateMock<ISearchService>();

         using (_mocks.Record())
         {
            Expect
                  .Call(mockService.GetCustomersByOrderCount(42))
                  .Return(this._fakeResults);
         }

         using (_mocks.Playback())
         {
            SearchPresenter presenter =
                  new SearchPresenter(_stubView, mockService);

            presenter.SearchByOrderCount(42);
         }
      }

      [Test]
      public void Search_results_are_displayed_to_the_user()
      {
         ISearchView mockView = _mocks.CreateMock<ISearchView>();

         mockView.SearchResults = _fakeResults;

         SetupResult
               .For(_stubService.GetCustomersByOrderCount(42))
               .Return(_fakeResults);

         _mocks.ReplayAll();

         SearchPresenter presenter = new SearchPresenter(mockView, _stubService);

         presenter.SearchByOrderCount(42);

         _mocks.Verify(mockView);
      }
   }

What I did here was to make running the search independent from displaying the search results. You’ll notice that each test uses a single mock. In the case of the second test I use a stub to stand in for the service; I don’t really care about the search service in this test, it’s just there to get the job done and return some dummy results.

So what’s the benefit of the single mock approach? Well, first it keeps your test-code cycle short. That is, by keeping your tests small you design less code before returning to test. This is absolutely key when adopting a continuous design philosophy. You don’t want to let things go to far or your discipline is likely to break down.

You’ve maybe heard the whole single assertion per test tip, right? Well a mock is really a type of assertion. You’re asserting get to callin’ this here code if you expect to pass. Stubs aren’t assertions. They’re more like saying: dear code under test, I need you to run so here’s a dummy that will get you to the scenario I need.

The main thing for me with this approach is that I get a higher quantity of smaller but more focused tests. It’s a small price to pay because your test code becomes a little more agile against the “real” code. When a small, well-named test breaks it’s easier to identify at a glance what broke it. This can be really handy in speeding you up when you’re refactoring or making behavioral changes to code in some other area of your test suite. Consider me wanting to introduce a caching layer or a dirty check on the view between getting search results and displaying them. These tests, beyond requiring a new constructor dependency, wouldn’t necessarily break or, at most, would require another stub. The nature of the behavior I’m testing (specified by the test name) simply does not change.

Also, yes it merits repeating, tiny tests equal more frequent test-code iterations equal better discipline equal better chance of sticking with TDD! This, for folks new to the technique, will greatly increase your chance and feelings of success.