Three Simple Steps to Improve Your Writing

Technical books are longer than they ought to be. Most software books could be improved by shedding a tenth of their heft. It's a product of market pressures, of course: Tech books need to get to market fast, which does not allow for the time-consuming labor of honing and refining a text until it is lean and tight. I have a few simple strategies, though—simple tips that provide a disproportionately beneficial return on a trivial time investment. You can use the following tips to improve your blog posts, books, and presentations.

Replace "basically" with nothing.


This word never adds value. It is usually a manifestation of the author's or speaker's unconscious concern that what he is explaining is too complex. If time allows, revise the material until your readers don't need extra convincing that it is basic. At least get rid of the useless word.

You could have some fun writing a regular expression to correct all instances with a global search-and-replace. If you're amused by the challenge, please feel free to post your regex in the comments. You'd be helping all of us.

Here are the replacements your regex would need to catch:
FindResult
Basically, it can start a sentence.It can start a sentence.
Basically people leave off the comma, too.People leave off the comma, too.
It can basically appear in the middle.It can appear in the middle.
It can, basically, be set off with commas.It can be set off with commas.
It can end a sentence, basically.It can end a sentence.
It might end without a comma basically.It might end without a comma.

Replace "essentially" with nothing.


As above.

Replace "is nothing more than" with "is."


The "is nothing more than" construction falls in the category of noisy hedge words. It's a large category. Folks add words to forestall arguments. Even though it sounds romantically brash—X is nothing but Y, #wristforehead—it actually weakens the association between the subject and its predicate nominative. Be clear; be bold. If you're trying to define X by saying that it is Y, say that X is Y.

I wish the industry allowed more time for editing. I wish I were able to help more people express their ideas. Good editing is liberating, plucking the brambles and cruft off a passage until its central theme floats to the fore—getting the text out of the way of the writing.

I hope you find these tips helpful and easy to implement. Ruthlessly delete useless clutter like "basically," "essentially," and "nothing more than." Let your ideas stand tall.

ReSharper Shortcut for Context-Sensitive Unit-Test Running

For a keyboard shortcut to the context-sensitive ReSharper unit test runner (otherwise available via right-click > Run Unit Tests), map:

ReSharper.ReSharper_UnitTest_ContextRun

(Thanks to Clinton for mentioning it.)

What This Solves


The slowest way to select and run unit tests is to click the green-yellow bubbles in the left margin and pick "Run" (or "Append to Session" to collect a bunch of them to run).



From the right-click menu, the "Run Unit Tests" option will run a test if your cursor is in a test, all tests in a fixture if your cursor is outside a test but within the fixture, or all tests in a file if you're outside any fixtures.

Mapping the ReSharper.ReSharper_UnitTest_ContextRun to a keyboard shortcut achieves the context-sensitive behavior, mouse free. I chose Alt-T for mine, since that wasn't in use for anything else. (Have a nice strategy for picking unique keyboard shortcuts and remembering them? Please share in the comments.)

To Map the Shortcut


Tools > Options > Environment > Keyboard. In the "Show commands containing" textbox, enter some or all of the command, and select the command.



Set your focus to the "Press shortcut keys" textbox and type your shortcut just as if you were invoking it. If a command shows up in the "Shortcut currently used by" list, life will be simpler if you pick a different shortcut. When you have one you like, click "Assign" and "OK." Good to go!

Rhino Mocks Examples, with a fix

Jon Kruger created an excellent explanation of Rhino Mocks, using unit tests to demonstrate and illuminate the syntax and capabilities. (Found via @gar3t.) It needs one small correction, which I'd like to write about here so that I can link to and support Jon's work, and because it gives the opportunity to clarify a subtle distinction between mocks and stubs and verified expectations.

First, go check out Jon's code, then come back here.

The problem lies in the following test. I can comment out the part that looks like it is satisfying the assertions, yet the test still passes—a false positive.

[Test]
public void Another_way_to_verify_expectations_instead_of_AssertWasCalled()
{
  var stub = MockRepository.GenerateStub<ISampleClass>();
 
  // Here I'm setting up an expectation that a method will be called
  stub.Expect(s => s.MethodThatReturnsInteger("foo")).Return(5);
 
  //Sneaky Sharon comments out the "Act" part of the test:
  //var output = stub.MethodThatReturnsInteger("foo");
  //Assert.AreEqual(5, output);
 
  // ... and now I'm verifying that the method was called
  stub.VerifyAllExpectations();
}

In translation, that test says: Create a fake ISampleClass; set up an expectation that a method will be called; call that method do nothing; verify that your expectations were met (and flag the test as a failure if they weren't). Shoot. Worse than not having my expectations met is not realizing they're not being met. Reminds me of my college boyfriend.

There are two things to fix here. The first is that this test is a little solipsistic. If you create a mock, tell the mock to act, and verify things about the mock... all you're testing are mocks. Instead, you want your tests to exercise real code. The "system under test," i.e., the class being tested, should be part of your production code. Its dependencies are what get mocked, so that you can verify proper interactions with those dependencies. Let's fix the solipsism before going on to the second issue.

As originally written, the expectation would be satisfied by the "Act" (as in Arrange-Act-Assert) part of the test. It says, "Call this method. Did I just call this method? Oh, good." Instead, you want to ensure the system under test correctly interacts with its friends, using Rhino Mocks' AssertWasCalled and Expect methods. We need a real class that takes the stubbed class and calls a method on the stubbed class, and we'll write unit tests around the real class.

public class MyRealClass
{
  public void ActOnTheSampleClass(ISampleClass sampleClass)
  {
  }
}

Here's the re-written test, verifying how my real class interacts with the ISampleClass interface.

[Test]
public void Another_way_to_verify_expectations_instead_of_AssertWasCalled()
{
  var stub = MockRepository.GenerateStub<ISampleClass>();
  var systemUnderTest = new MyRealClass();
 
  // Here I'm setting up an expectation that a method will be called
  stub.Expect(s => s.MethodThatReturnsInteger("foo")).Return(5);
 
  // Tell the system to act (which, if it is working correctly, 
  // will call a method on the ISampleClass.
  systemUnderTest.ActOnTheSampleClass(stub);
 
  // ... and now I'm verifying that the method was called
  stub.VerifyAllExpectations();
}

This test will still pass, despite the fact that my real class does not currently call any methods on the ISampleClass interface. This points to the second issue to fix. In Rhino Mocks, expectations on stubs are not verified; only mocks are verified. If an object is created with GenerateStub instead of GenerateMock, then its VerifyAllExpectations method doesn't do anything. This is non-obvious because the AssertWasCalled and AssertWasNotCalled methods on a stub will behave the way you want them to.

In Rhino Mocks, a stub can keep track of its interactions and assert that they happened, but it cannot record expectations and verify they were met. A mock can do both these things.

That is how they are implemented in Rhino Mocks. If you were holding firm to the ideas in Fowler's Mocks Aren't Stubs article, I think stubs would implement neither VerifyAll nor AssertWasCalled. Semantically, verifying expectations and asserting interactions are synonymous, if you ask me; therefore, stubs shouldn't do either one.

Back to Jon Kruger's tests. If we call GenerateMock instead of GenerateStub, the test will fail properly with an ExpectationViolationException.

[Test]
public void Another_way_to_verify_expectations_instead_of_AssertWasCalled()
{
  var stub = MockRepository.GenerateMock<ISampleClass>();
  var systemUnderTest = new MyRealClass();
 
  // Here I'm setting up an expectation that a method will be called
  stub.Expect(s => s.MethodThatReturnsInteger("foo")).Return(5);
 
  // Tell the system to act (which, if it is working correctly, 
  // will call a method on the ISampleClass.
  systemUnderTest.ActOnTheSampleClass(stub);
 
  // ... and now I'm verifying that the method was called
  stub.VerifyAllExpectations();
}

Now that we're red, let's get to green. Change the system under test so that it does its job as expected.

public class MyRealClass
{
  public void ActOnTheSampleClass(ISampleClass sampleClass)
  {
    sampleClass.MethodThatReturnsInteger("foo");
  }
}

Wahoo, a passing test that we can rely on.

The two key points from this exercise are:
  1. Describing Rhino Mocks with unit tests is a cool way to explain a topic. Let's have more executable documentation, eh?
  2. Expectations on stubs aren't verified, so beware of falsely passing tests.

GirlWritesCode is moving to new digs; please join us.

I use Blogger's FTP model, where my posts are published out to my webhost on Invisible City. Blogger is discontinuing that service, due to lack of use and to enable bigger and better things in their architecture. So I need to shuffle things around, and I hope that you will follow this blog to its new home.

I'll update GirlWritesCode.com to redirect to the new location, so if that's the url you've bookmarked, you're good to go.

I'll continue to cross-post at Los Techies. If that's your main means of keeping up with me, then... how are you reading this? ;-)

I'll have an RSS feed from the new location, but the url is going to change. It will be http://girlwritescode.blogspot.com/atom.xml, I'm pretty sure. [Correction: http://www.girlwritescode.com/feeds/posts/default] I'll post a "we've landed" post from the new location, so you'll know when I've got it sorted.

I appreciate your readership. Everything I write, I write with you in mind. I hope you will follow this blog to its new location.

More Dogs and Bears and Chickens and Things: Invite your colleagues to Pablo's Fiesta

If you work with developers who are women, please tell them about the Los Techies Open Space conference, coming up at the end of February. If you've attended an event like this in the past, you're already aware of some facts:
  • The Austin developer community is vibrant, engaged, and constantly striving to improve our craft. We've got a good thing going here.
  • The quality of the conversations and the value of the event far outstrip the price of admission; it would be a bargain at twice the price.
  • Women are way under-represented.

Early in my career, I wasn't tapped into the information channels that announce events like this. I didn't go because I just didn't know about them. My friend and colleague Josh Flanagan made a point of letting me know, and encouraging me to go, and showing that it was not only okay but right to ask my employer to send me to such things.

Attending conferences has made a huge difference in my growth as a developer and in my career. It brought me into the on-going conversation in the developer community. It exposed me to new practices and new technologies, which I brought back to the team. Please do the same favor for your women co-workers that Josh did for me: Tell them about Pablo's Fiesta and encourage them to sign up.

Bringing women into the mix brings new, diverse ideas into the conversation, new skillsets to the community, more role models for our kids. The conference will be improved by spicing up the guest list. Although I'm focusing on women here, reach out to any of your colleagues who "don't usually go to these things." New voices mean new synergy, which means more learning and more fun.

And you. Sign up, your own self. It'll be great.

If you have any questions about Pablo's Fiesta, or about whether you'd enjoy it, please feel free to post them here, and I'll get the answers for you.

Interface-Oriented Design - Book Review

Ken Pugh's Interface-Oriented Design (Pragmatic Programmers) presents an approach to designing applications that focuses first on the interfaces, the places where pieces of the application interact. The interfaces here are not primarily user interfaces, but module-to-module interfaces and service interfaces, and the applications are not exclusively object-oriented. Pugh's proposed process is to identify use cases and test cases, determine the interfaces that will enable those use cases, then create tests and implementations for the interfaces.

The book is divided into three parts. The first explains the concepts and theory underlying an interface-focused approach to design. These concepts include real-world analogies which quickly provide context to the discussion; types of interfaces, such as stateless versus stateful, and procedural versus document; design concerns such as contracts, cohesiveness, and polymorphism; and the Asimov-inspired "three laws of interfaces," which specify the qualities of a well behaved implementation. Part two is brief and describes where interface-oriented design fits into the project lifecycle. Part three walks through three examples, from concept to design to implementation, and highlights the design patterns exhibited in those examples. The book concludes with a grab-bag appendix of topics that could have been better served by integration into the main text.

If your learning style is learn-by-doing, you might get more out of the book by reading Part Three before Part One. Part Three provides the "yeah, but what are we doin' here" skeleton onto which you can hang the theory that is explained in Part One. I find theory easier to digest and retain if I know which of my real-world, day-to-day experiences it applies to. You'll get that context if you flip the order in which you read it.

I picked up this book looking for best practices on providing and consuming remote interfaces, and it isn't that. Have you ever taken a sip of something you like, but because you were expecting a completely different flavor, it tasted off? I bumped into that dissonance here, so it was hard for me to get into the book. To appropriately prepare your palate, the flavor to anticipate from Interface-Oriented Design is a technique for thinking about a problem domain and its software solution by thinking about the places where responsibilities interact, analogous to the way that service-oriented architecture is a technique for thinking about software design.

An area where this book really shines is Pugh's deft use of real-world examples. In the first chapter, he introduces the process of ordering a pizza as a series of exchanges through a PizzaOrdering interface. The example is familiar, relatable, and practically identical across the United States (implementations vary, of course). Pugh then uses that example and expands upon it throughout the rest of the book, allowing us to fit new concepts into the model as it is refined. This worked better than if each new concept had been presented with a new example; the book gained a pedagogical momentum.

Many times during my reading, I asked myself whether the ideas were so fundamental and distilled as to shift my way of thinking, or so fundamental as to be mundane and trivial. Was this book raising the level of abstraction, like climbing a mountain to get a better view of the landscape, or just telling me no-duh stuff I already knew? Is its audience experienced developers looking to put terms and practices around habits they do instinctively, or is its audience beginners who need an introduction to methodical design? I still haven't decided. Will it affect my thinking? Probably. Not in ways that I can articulate and enumerate for you, but likely in subtle and profound ways that I may or may not notice as they occur. For yourself, I recommend checking out the table of contents (available from the Pragmatic Bookshelf) and see if it suits you.

Happy Hack-o-ween: Electronics and a microcontroller spice up the haunt

Ah, Halloween, when a young woman's fancy turns to love. And zombies.

I had two personal requirements for the costume I would build this year:
  1. It shall be spooky.
  2. It shall blink.


I'll tell you about the final result, the electronics and the software that went into it, plus the techniques I used to achieve wearable electronics. I'll introduce you to the Arduino, an open-source microcontroller prototyping platform, which is an exhilarating tool/toy for making your software skills manifest in the physical world.

My husband and I have been teaching ourselves electronics. A few months ago, Dad taught me to solder. I recently read Syuzi Pakhchyan's excellent primer on wearable electronics and smart materials, Fashioning Technology. And I've been making things with my Arduino. All these ideas were swirling and combining in my head to inspire this year's Halloween project. Er, costume. Same difference.

What was I? I was a nightmare... the thing under your bed... the reason for your well developed sense of paranoia...
The thing under your bed

I sported a crop of writhing eyeballs erupting from my head. Each eyeball has an LED inside it, and they blink randomly and independently, until I trigger a hidden switch, which causes the blinky ones to go dark and two red eyes to pulse menacingly. In the Flickr photoset, you can see the construction process.

The Arduino Sketch


The term "Arduino" is overloaded to mean:
  1. a particular chip and circuit board which you can buy or build;
  2. the IDE in which you write programs for the chip;
  3. the language, which is C-flavored;
  4. fun.


Arduino programs are called sketches. Every sketch must contain two functions: setup (runs once) and loop (runs continuously). Here's my sketch, with extra explanatory comments, that blinks the six regular eyeballs and responds to the switch by pulsing the red eyeballs.
    1 #define SWITCH 8
    2 int ledPins[] = {2, 3, 4, 5, 6, 7};
    3 const int ledPinsCount = 6;
    4 int redEyePins[] = {10, 11};
    5 const int redEyePinsCount = 2;
    6 long durations[ledPinsCount];
    7 int ledStates[ledPinsCount];
    8 long previousTimes[ledPinsCount];
    9 int i;
   10 
   11 void setup()
   12 {
   13   pinMode(SWITCH, INPUT); //Specify the switch pin as an input.
   14 
   15   for (i = 0; i < redEyePinsCount; i++)
   16   {
   17     pinMode(redEyePins[i], OUTPUT); //Specify each red-eye LED pin as an output.
   18   }
   19 
   20   for(i = 0; i < ledPinsCount; i++)
   21   {
   22     pinMode(ledPins[i], OUTPUT); //Specify each regular LED pin as an output.
   23     ledStates[i] = random(1); //Randomly set the LEDs to on or off (1 or 0).
   24     durations[i] = GetRandomDuration(); //Define a random duration for each LED to stay in that state.
   25     previousTimes[i] = 0; //At time of setup, the "last time we changed" is at 0 milliseconds, the start of time.
   26   }
   27 }
   28 
   29 void loop()
   30 {
   31   if (digitalRead(SWITCH) == HIGH)
   32   {
   33     TurnOffLeds();
   34     PulseRedEyes();
   35   }
   36   else
   37   {
   38     for(i = 0; i < redEyePinsCount; i++)
   39     {
   40       digitalWrite(redEyePins[i], LOW); //Turn the red eyes all the way off.
   41     }
   42 
   43     for(i = 0; i < ledPinsCount; i++) //For each LED:
   44     {
   45       if (millis() - previousTimes[i] > durations[i])
   46       {
   47         ChangeLed(i); //If this one's duration is up, then flip it.
   48       }
   49     }
   50   }
   51 }
   52 
   53 void TurnOffLeds()
   54 {
   55   for(i = 0; i < ledPinsCount; i++)
   56   {
   57     digitalWrite(ledPins[i], LOW);
   58   }
   59 }
   60 
   61 void PulseRedEyes()
   62 {
   63   //Fade on, then off.
   64   int j;
   65   for(j = 0; j < 255; j+=5)
   66   {
   67     for(i = 0; i < redEyePinsCount; i++)
   68     {
   69       analogWrite(redEyePins[i], j);
   70       delay(10);
   71     }
   72   }
   73   for(j = 255; j > 0; j-=5)
   74   {
   75     for(i = 0; i < redEyePinsCount; i++)
   76     {
   77       analogWrite(redEyePins[i], j);
   78       delay(10);
   79     }
   80   }
   81 }
   82 
   83 void ChangeLed(int ledPin)
   84 {
   85   previousTimes[ledPin] = millis(); //Update the "last time we changed" to now.
   86   durations[ledPin] = GetRandomDuration(); //Give it a new random duration.
   87   ledStates[ledPin] = 1 - ledStates[ledPin]; //Flip the state between on and off.
   88   digitalWrite(ledPins[ledPin], ledStates[ledPin]); //Set the LED to that state.
   89 }
   90 
   91 long GetRandomDuration()
   92 {
   93   //Random number between 1 and 10, then multiplied by 400 to give it a detectable duration.
   94   return random(1, 10) * 400;
   95 }


I like the way the eyes blink independently. If they all flashed in unison, they would look like Christmas lights, and you would notice that two were "special" because they weren't flashing. Instead, the duration that any given eyeball is lit or dark constantly changes.

The blinking is managed by a collection of arrays. One array represents each of my LED pins, so that I can address them in a for loop. The three other arrays hold: the state (on/off) of each LED; the duration each LED should stay in that state; the reading from the millisecond counter when the LED last flipped its state. Each time the loop function executes, if the switch is not connected, then I look at each LED; if the difference between the current time and the time when it previously changed is greater than its duration, flip its state (from off to on, or from on to off), randomly assign it a new duration, and record "now" as the new "previously changed" time. If the switch is connected, then I make the red eyes fade on and fade off.

Fading with PWM


PWM (Pulse-Width Modulation) is a technique for making a digital component (one that turns on or off) simulate analog behavior (be a little bit on, and then a little bit more on). If you turn an LED off and on really quickly, you won't perceive the flickering, but it will look half as bright, because it is actually off for half the time. If you let it spend a little more time off than on, it will appear even dimmer. So by varying the width of the pulses, you can control how bright the LED looks.

The Arduino comes with built-in PWM functions; some pins are already set up to be PWM pins. If you plug an LED into one of the PWM pins, then you can write to it as if it were an analog component. That's why, in my sketch above, I set the brightness of the red eyes using analogWrite(), instead of digitalWrite(). My for loop increments the counter j from 0 to 255, and sets the brightness of both red eyes to the value of j. The Arduino takes care of (imperceptibly) flickering the LEDs with the right ratio of on-time and off-time to achieve a j amount of brightness. So the eyes get gradually brighter, then gradually dimmer. (Then control returns to the main loop function, but if my switch is still connected, the red eyes will throb again.)

Snaps: Wearable Plugs


A metal sewable snap is like a plug for your clothing, an interface between the world of textiles and the world of wires. This is handy when you need the electronics to be separate while you are getting into the clothing, or if you want to wash the clothing. My Arduino hung out at the base of my neck, to be near the LEDs on my head but hidden underneath my wig, but my control switch was near my hip. I could have run a wire down to the switch, but conductive thread was more subtle and more comfortable.

To complete the connection, I soldered a short wire to one side of the snap. That wire plugged into a pin on the Arduino. The conductive thread ran from the switch at my hip up to the back of my dress near the Arduino, and I sewed that conductive thread to the other half of the snap. When the two halves are snapped together, the wire and the thread make a complete connection, as if they were one continuous wire.
Soldered snaps / Sewn snaps

I had two threads (going out to the switch and back), so I encased them each in a bias tape tube, to prevent them from touching each other and shorting out.

I've been saying "switch," but actually, I simplified at the 11th hour. I tied each thread around a safety pin, and stuck the pins to my dress. When the safety pins touched each other, they completed the circuit, which the Arduino sketch interpreted as triggering the switch—cue red-eye glare.

What's Next


Soldering and sewing are both liberating skills to possess—they free up your creativity to make wilder and more integrated stuff. If you are currently proficient with only one, ask around and see if you can find a buddy who's good at the other, and teach each other.

The Arduino comes with a great community of hackers and makers, lots of people to learn from and collaborate with. Definitely check it out. There is lots of fun to be had, and blinking LEDs is the barest beginning of what it can do.

Refactoring Dinner: Interfaces instead of Inheritance

Last time, in Cooking Up a Good Template Method, I had a template method cooking our dinner. An abstract base class defined the template—the high level steps for preparing a one-skillet dinner—and a derived class provided the implementation for those steps. I'm currently reading Ken Pugh's Interface Oriented Design (more on that after I finish the book), and it got me thinking of a way to change the design to use interfaces instead of inheritance.

I think there's value in this refactoring because it allows future flexibility and testability. Let's stroll through it, and I welcome your thoughts about how (and whether) this improves the code.

Previously, we had a base class SkilletDinner, which was extended by variants on that theme, such as chicken with onions and bell peppers or the FancyBaconPankoDinner. (If I've learned one thing from my readership, it is that blog posts should mention bacon. Mm, crispy bacon.) As the first step in the refactoring, I'll create an interface, ISkilletCookable that provides the same methods that were previously abstract methods in SkilletDinner. By naming convention, the interface is prefixed with 'I' and is an adjective describing how it can be used (-able).
    4   public interface ISkilletCookable
    5   {
    6     void HeatFat();
    7     void SauteSavoryRoot();
    8     void SauteProtein();
    9     void SauteVegetables();
   10     void AddSauceAndGarnish();
   11   }


Next, I'll create a SkilletDinner constructor that accepts an ISkilletCookable, and change the SkilletDinner's Cook() method to ask that cookable to do the work. SkilletDinner no longer needs to be abstract.
    5   public class SkilletDinner
    6   {
    7     private readonly ISkilletCookable cookable;
    8 
    9     public SkilletDinner(ISkilletCookable cookable)
   10     {
   11       this.cookable = cookable;
   12     }
   13 
   14     public void Cook()
   15     {
   16       cookable.HeatFat();
   17       cookable.SauteSavoryRoot();
   18       cookable.SauteProtein();
   19       cookable.SauteVegetables();
   20       cookable.AddSauceAndGarnish();
   21     }
   22   }


Then, FancyBaconPankoDinner implements ISkilletCookable and provides implementations for each of the methods that will be called by the Cook() method.

The first benefit from this refactoring is flexibility. While FancyBaconPankoDinner could not have inherited multiple classes (no multiple inheritance in C#), it can implement multiple interfaces. For example, it could also implement the IShoppable interface, thereby providing a ListIngredients() method that would let me include it in my grocery list.

This refactoring also makes it easier for me to test the quality and completeness of my template method. I can verify—does it cover all of the requisite steps for cooking a skillet dinner?—by creating behavior-verifying tests that assess the SkilletDinner's interactions with the ISkilletCookable interface. When I'm writing unit tests for the SkilletDinner class, I want to test its behavior because the behavior is what's important.

To forestall objections, I tried writing a test around the old version, creating my own mock class that extends the old abstract SkilletDinner. It got pretty lengthy.
    4   public class SkilletDinnerSpecs
    5   {
    6     [TestFixture]
    7     public class When_told_to_cook
    8     {
    9       const string heatFatMethod = "HeatFat";
   10       const string sauteSavoryRootMethod = "SauteSavoryRoot";
   11       const string sauteProteinMethod = "SauteProtein";
   12       const string sauteVegetablesMethod = "SauteVegetables";
   13       const string addFinishingTouchesMethod = "AddFinishingTouches";
   14 
   15       [Test]
   16       public void Should_follow_dinner_preparation_steps_in_order()
   17       {
   18         var systemUnderTest = new MockSkilletDinner();
   19 
   20         var expectedMethodCalls = new List<string>();
   21         expectedMethodCalls.Add(heatFatMethod);
   22         expectedMethodCalls.Add(sauteSavoryRootMethod);
   23         expectedMethodCalls.Add(sauteProteinMethod);
   24         expectedMethodCalls.Add(sauteVegetablesMethod);
   25         expectedMethodCalls.Add(addFinishingTouchesMethod);
   26 
   27         systemUnderTest.Cook();
   28 
   29         Assert.AreEqual(expectedMethodCalls.Count, systemUnderTest.CalledMethods.Count, "Expected number of called methods did not equal actual.");
   30 
   31         for (int i = 0; i < expectedMethodCalls.Count; i++)
   32         {
   33           Assert.AreEqual(expectedMethodCalls[i], systemUnderTest.CalledMethods[i]);
   34         }
   35       }
   36 
   37       private class MockSkilletDinner : SkilletDinner
   38       {
   39         public readonly List<string> CalledMethods = new List<string>();
   40 
   41         protected override void HeatFat()
   42         {
   43           CalledMethods.Add(heatFatMethod);
   44         }
   45 
   46         protected override void SauteSavoryRoot()
   47         {
   48           CalledMethods.Add(sauteSavoryRootMethod);
   49         }
   50 
   51         protected override void SauteProtein()
   52         {
   53           CalledMethods.Add(sauteProteinMethod);
   54         }
   55 
   56         protected override void SauteVegetables()
   57         {
   58           CalledMethods.Add(sauteVegetablesMethod);
   59         }
   60 
   61         protected override void AddFinishingTouches()
   62         {
   63           CalledMethods.Add(addFinishingTouchesMethod);
   64         }
   65       }
   66     }
   67   }


In the new design, I can mock the ISkilletCookable interface with a mocking framework like Rhino.Mocks. The interface is easy to mock because interfaces, being the epitome of abstractions, readily lend themselves to being replaced by faked implementations. Rhino.Mocks takes care of recording and verifying which methods were called.
    7   public class SkilletDinnerSpecs
    8   {
    9     [TestFixture]
   10     public class When_told_to_cook
   11     {
   12       [Test]
   13       public void Should_follow_dinner_preparation_steps_in_order()
   14       {
   15         var mocks = new MockRepository();
   16         var cookable = mocks.StrictMock<ISkilletCookable>();
   17         var systemUnderTest = new SkilletDinner(cookable);
   18 
   19         using (mocks.Record())
   20         {
   21           using (mocks.Ordered())
   22           {
   23             cookable.HeatFat();
   24             cookable.SauteSavoryRoot();
   25             cookable.SauteProtein();
   26             cookable.SauteVegetables();
   27             cookable.AddSauceAndGarnish();
   28           }
   29         }
   30         using (mocks.Playback())
   31         {
   32           systemUnderTest.Cook();
   33         }
   34       }
   35     }
   36   }


The test relies on Rhino.Mocks to create a mock implementation of ISkilletCookable, and then verifies that the system under test, the SkilletDinner, interacts correctly with ISkilletCookable by telling it what steps to do in what order.

That test is quite cognizant of the inner workings of the SkilletDinner.Cook() method, but that's specifically what I'm unit testing: Does the template method do the right steps? I don't mind how the steps are done, but you have to start the onions before you add the meat, or else the onions won't caramelize and flavor the oil.

By the way, if you had previously found the learning curve for Rhino.Mocks' record/playback model too steep a hill to climb (or to convince your teammates to climb), check out Rhino.Mocks 3.5's arrange-act-assert style. It creates more readable tests, putting statements in a more intuitive order. I really like it. I could not, however, use it here because I have not found a way to enforce ordering of the expectations (i.e., to assert that method A was called before B, and to fail if B was called before A) in A-A-A-style. So we have a record/playback test, instead.

Here's a summary of the refactoring. I extracted an interface, ISkilletCookable, and composed SkilletDinner with an instance of that interface, liberating us from class inheritance. Because SkilletDinner is now given the worker it depends on (via dependency injection), I can give it a fake worker in my tests, so that my unit tests don't need to perform the time- and resource-consuming operation of firing up the stove. And I managed to write another blog post that mentions bacon. Mm, bacon.

Cooking Up a Good Template Method

The software concept of "raising the level of abstraction" has improved my skill and creativity in cooking, by teaching me to think about recipe components in terms of their properties and functions. Practicing abstraction-raising in cooking feeds back to help me with coding; for example, keeping me from going astray the other day with the Template Method pattern. This post is more about coding than cooking. The cooking's a metaphor. (The cake is a lie.)

Abstract Cooking
My skill with cooking grew from rote recipe following to intuitive creation when I started to think of it in terms borrowed from software: raising the level of abstraction.

Consider a week-night skillet dinner. If I told you to heat canola oil in a cast-iron skillet, saute slices of onion and chunks of chicken seasoned with salt and pepper, and toss in bell peppers cut into strips, you could probably follow along and make exactly that. But that's pretty limiting. If instead I described the process as using a fat to conduct heat for sauteing a savory root, a seasoned protein, and some vegetables, then you could use that as a template, and make a week of dinners without repeating yourself.

Let's dive into that step of using a fat for conduction, because it is a cool and useful bit of food science. To cook, you need to get heat onto food. The medium can be air, liquid, or fat. Each creates different results, hence the terms baking, boiling, and frying. When you toss cut-up bits of food in a skillet with oil and repeatedly jostle them, you're sauteing ("saute" means "to jump"), and that oil is playing the role of the fat, which is conducting the heat. If you'll pardon the metaphor, CanolaOil implements the IFat interface.

It's useful to think of cooking this way, because if you know the properties of the various cooking fats, you can choose the right IFat implementation for the job. Canola oil is heart-healthy and stands up well to stove-top heat. Olive oil has wonderful health benefits, a bold flavor, and an intriguing green color, but those attributes are pretty much obliterated by heat, so save your expensive EVOO for raw applications like salads and dips. Butter makes everything taste better, browns up beautifully, but is harder on the heart and will burn at a low temperature; temper it with an oil like canola to keep it from burning. Peanut oil stands up to heat like a champ, so it's popular for deep frying. Armed with this kind of knowledge, I don't need to check a recipe when I'm cooking; I just think about what I'm trying to accomplish, and choose the right implementation.

Pam Anderson's How to Cook Without a Book got me thinking about food this way, and Harold McGee's On Food and Cooking provides a feast of food geekery to fill in all the particulars.

Template Coding
Thinking about food this way, raising the level of abstraction, guides my thinking about code. My meal preparation follows the Template Method pattern, as does a class my teammate and I needed to modify recently.

In this example, our application sends instructions to various external systems. The specifics of how those systems like to hold their conversations vary between systems. However, the series of steps, when phrased in our core business terms, remain the same. You do A, then you do B, then you do C, in whatever way a particular instance likes to do A, B, and C.

Here's my class with its template method, translated back to the dinner metaphor:

    3     public abstract class SkilletDinner

    4     {

    5         public void Cook()

    6         {

    7             HeatFat();

    8             SauteSavoryRoot();

    9             SauteProtein();

   10             SauteVegetables();

   11         }

   12 

   13         protected abstract void HeatFat();

   14         protected abstract void SauteSavoryRoot();

   15         protected abstract void SauteProtein();

   16         protected abstract void SauteVegetables();

   17     }


But lo, I encountered an external system that needed to do one extra little thing. I needed a special step, just for that one instance. Like dinner the other night, where the vegetable was asparagus, the fat was bacon (oh ho!), and the final step was to toss some panko breadcrumbs into the pan to brown and toast and soak up the bacony love.

How do I extend my template method to accommodate an instance-specific step?

One idea that floated by was to make the method virtual, so that we could override it in our special instance. But we still wanted the rest of the steps, so we'd have to copy the whole method into the new instance, just to add a few lines. Also, anybody else could override that template, too, so that when they were told to do A, B, and C, they could totally fib and do nothing of the sort.

    3     public abstract class SkilletDinner

    4     {

    5         public virtual void Cook()

    6         {

    7             //Note: The Cook template method is now virtual,

    8             //and can be overridden in deriving classes.

    9             //That's not good.

   10             HeatFat();

   11             SauteSavoryRoot();

   12             SauteProtein();

   13             SauteVegetables();

   14         }

   15         protected abstract void HeatFat();

   16         protected abstract void SauteSavoryRoot();

   17         protected abstract void SauteProtein();

   18         protected abstract void SauteVegetables();

   19     }

   20 

   21     public class LazyDinner : SkilletDinner

   22     {

   23         public override void Cook()

   24         {

   25             OrderPizza();

   26             //We're overriding the template and *cheating*!

   27             //Although, if it's Austin's Pizza,

   28             //maybe that's okay...

   29         }

   30 

   31         private void OrderPizza()

   32         {

   33             //With extra garlic!

   34         }

   35 

   36         protected override void HeatFat() { }

   37         protected override void SauteSavoryRoot() { }

   38         protected override void SauteProtein() { }

   39         protected override void SauteVegetables() { }

   40     }


That LazyDinner class isn't really a SkilletDinner at all; its behavior is completely different. No, that option flouts the whole point of the Template Method pattern.

Our better idea was to make one small change to the template method, adding an extension point. That is, a call to a virtual method which in the base implementation does nothing, and can be overridden and told to do stuff in specific cases.

Back to dinner:

    3     public abstract class SkilletDinner

    4     {

    5         public void Cook()

    6         {

    7             HeatFat();

    8             SauteSavoryRoot();

    9             SauteProtein();

   10             SauteVegetables();

   11             AddFinishingTouches(); //Here's the hook.

   12         }

   13 

   14         protected virtual void AddFinishingTouches()

   15         {

   16             //By default, do nothing.

   17         }

   18 

   19         protected abstract void HeatFat();

   20         protected abstract void SauteSavoryRoot();

   21         protected abstract void SauteProtein();

   22         protected abstract void SauteVegetables();

   23     }

   24 

   25     public class FancyBaconPankoDinner : SkilletDinner

   26     {

   27         protected override void AddFinishingTouches()

   28         {

   29             //In this case, override this extensibility hook:

   30             ToastBreadcrumbs();

   31         }

   32 

   33         private void ToastBreadcrumbs()

   34         {

   35             //Toss in the bacon fat; keep 'em moving.

   36         }

   37 

   38         protected override void HeatFat()

   39         {

   40             //Cook bacon, set aside, drain off some fat.

   41         }

   42 

   43         protected override void SauteSavoryRoot()

   44         {

   45             //Minced garlic, until soft but before browning

   46         }

   47 

   48         protected override void SauteProtein()

   49         {

   50             //How about... tofu that tastes like bacon?

   51         }

   52 

   53         protected override void SauteVegetables()

   54         {

   55             //Asparagus, cut into sections.

   56             //Make it bright green and a little crispy.

   57         }

   58     }


This maintains the contract of the template method, while allowing for special cases. With the right extensibility hooks in place, my dinner preparation happily follows the Open-Closed Principle—open for extension, but closed for modification.

I enjoy the way my various hobbies feed into and reflect upon each other. I hope this post has given you some useful insight into the Template Method pattern, or dinner preparation, or both. Look for synergies amongst your own varied interests; it can be the springboard for some truly breakthrough ideas.

Mmm, bacon...

Inconvenient Accessibility Makes Self-Documenting Code

Intentional use of access modifiers (public, private, etc.) is like a clear memo to your team. This came up during Steve Bohlen's Virtual Alt.Net talk on domain-driven design.

Steve explained the distinction between Entity objects, which have a unique identity independent of their properties (Even when I change my name, I'm still me.), and Value objects, which are defined by their properties (If you change the house number in an address, you have a new address.). When dealing with Entities, code should not be able to change the unique id—that would be like someone claiming your social security number and thereby becoming you. Therefore, Entity classes should have private setters for their unique identifiers.

A meeting attendee asked why, since this gets inconvenient when you're creating an object based on a record fetched from the persistence repository. It's a big pain; why bother? The analogy I would offer is this. When you're defining a class to represent an Entity in your business domain, you know it's an Entity. You intend for it to behave and be treated like an Entity. You don't want any of your teammates setting its unique id in their code. So you send them an email: "Don't set Person.UniqueId, okay?" Uh hunh. How well is that going to work over time?

Instead, if you simply don't provide a public accessor to the UniqueId property, your teammates will get the message loud and clear. Granted, someone could edit the code and change the accessibility, but the fact that he or she needs to is a flashing neon sign saying "Stop. Think. Are you barking up the wrong tree?" You've made your code communicative. Its structure conveys your intent. No need for comments; this is an example of self-documenting code.