Monday, January 14, 2008

Making the permanent move

I'm getting pretty tired of cross-posting, so I'm making the permanent move over to Los Techies.  After all, if I get a free t-shirt:

Then the least I can do is stop dipping my toe in the pool and just jump in.  Cross-posting is for chumps anyway.

You don't need to update your feeds, except the feed now links to Los Techies.  This will be my last post on the blogspot site (sniff, sniff), and while you treated me well blogspot, your name doesn't rhyme with a tasty, tasty beer.

Thursday, January 10, 2008

Converting tests to specs is a bad idea

When I first started experimenting with BDD, all the talk about the shift in language led me to believe that to "do BDD" all I needed to do was to change my "Asserts" to some "Shoulds".  At the root, it looked like all I was really doing was changing the order of my "expected" and "actual".

In my admittedly short experiences so far, I've found that BDD is much more than naming conventions, language, and some macros.  For me, unit testing was about verifying implementations while specifications were about specifying behavior.  Although I'm not supposed to test implementations with unit testing, conventions led me down this path.  It's easy to fall into the trap of testing implementations, given constraints we put on ourselves when writing unit tests.

Starting with tests

Typically, my unit tests looked something like this:

[TestFixture]
public class AccountServiceTests
{
    [Test]
    public void Transfer_WithValidAccounts_TransfersMoneyBetweenAccounts()
    {
        Account source = new Account();
        source.Balance = 100;

        Account destination = new Account();
        destination.Balance = 200;

        AccountService service = new AccountService();

        service.Transfer(source, destination, 50);
        
        Assert.AreEqual(50, source.Balance);
        Assert.AreEqual(250, destination.Balance);
    }
}

When I wrote the implementation test-first, I first got a requirement or specification from the business.  It sounded something like "We want to be able to transfer money between two accounts".

Before I started writing my tests, I had to figure a few things out.  Our naming conventions forced us into a path that made us choose where the behavior was supposed to reside, as we named our test fixtures "<ClassUnderTest>Tests".  In the example above, we're testing the "AccountService" class.  Additionally, our individual tests were named "<MethodName>_<StateUnderTest>_<ExpectedBehavior>".  We took these naming conventions because it organized the class behavior quite nicely according to members.

Converting to BDD syntax

I wanted to try BDD, so the quickest way I saw to do it was to change the names of our tests and switch around our assertions:

[TestFixture]
public class AccountServiceTests
{
    [Test]
    public void Transfer_WithValidAccounts_ShouldTransfersMoneyBetweenAccounts()
    {
        Account source = new Account();
        source.Balance = 100;

        Account destination = new Account();
        destination.Balance = 200;

        AccountService service = new AccountService();

        service.Transfer(source, destination, 50);

        source.Balance.ShouldEqual(50);
        destination.Balance.ShouldEqual(250);
    }
}

Now that I see the word "Should" everywhere, that means I'm doing BDD, right?

Just leave it alone

BDD is much more than naming conventions and the word "should", it's more about starting with a context, then defining behavior outside of any hint of an implementation.  When creating my Transfer test initially, before I could start writing ANY code, because of our naming conventions I had to decide two things:

  • What class does the behavior belong
  • What method name should be assigned to the behavior

But when writing true BDD-style specs, I don't care about the underlying class or method names.  All I care about is the context and specifications, and that's it!  If I was writing the Transfer behavior BDD-first, I might end up with this:

[TestFixture]
public class When_transfering_money_between_two_accounts_with_appropriate_funds
{
    [Test]
    public void Should_reflect_balances_appropriately()
    {
        Account source = new Account();
        source.Balance = 100;

        Account destination = new Account();
        destination.Balance = 200;

        source.TransferTo(destination, 50);

        source.Balance.ShouldEqual(50);
        destination.Balance.ShouldEqual(250);
    }
}

The key difference here is nowhere in the fixture nor the test method name will you find any mention of types, member names, or anything that hints at an implementation.  I'm driven purely by behavior, which led me to a completely different design than my test-first design.  In the future, if I decide to change the underlying implementation, I don't need to do anything with my BDD specs.  When I've decoupled my implementation of behavior completely from the specification of behavior, I can make much more dramatic design changes, as I won't be bound by my tests.

I've also found I don't modify specifications nearly as much as I used to modify tests.  If behavior is changed, I delete the original spec and add a new one.

So don't trick yourself into thinking that you need to modify your tests to become BDD-like.  Just leave those tests alone, they're doing exactly what they're designed to do.  A single context is likely split across many, many test fixtures, so it's just not an exercise worth undertaking.  Start your BDD specs fresh, unencumbered from existing test code, and the transition will be much, much easier.

Stop the Flash insanity

More and more it seems high-profile websites are using Flash as a mechanism to deliver essential content.  In extreme cases, such as mycokerewards, the entire site is built on Flash.  Ads in websites, which you used to be able to ignore, now use Flash to replace the entire screen contents, screaming at you to "GO SEE CLOVERFIELD!!!".

My dev machine is a fairly hefty beast, but it still has a hard time processing Flash-only sites:

I'm not even doing anything in the Flash-only site except that I'm looking at it.  It's doing some ridiculous, pointless animation of bubbles floating around, and that requires 40% of my dual-core machine's resources.  When I look at this site on a single-core machine, I pretty much can't use FireFox any more, as it's completely consumed with those floating bubbles.

Sites that used to be relatively easy to get around are now just annoying, like ESPN.com, which are starting to rely heavily on Flash to deliver actual content.  Please don't start playing some highlights video if I'm just going to your homepage, I really don't like Stuart Scott screaming "BOOYAH" to me through my speakers.

If anything, Flash should be use to complement content, but not be the actual content.  To deal with normal annoyances, I go back and forth between these two FireFox add-ons:

  • Adblock Plus (blocks ad content, but not other Flash content)
  • Flashblock (blocks ALL Flash content, letting you opt-in to anything you want to see)

Flash for delivering ad content is perfectly fine, as long as it's non-intrusive and non-resource intensive.  Flash for delivering site content is just plain heinous, and I hope Santa delivers coal in those perpetrators' stockings next year.

Wednesday, January 9, 2008

More on Scrummerfall

A couple of comments have led me to think that I didn't explain what it is.  Let's review waterfall phases:

  • Requirements specifications
  • Design
  • Implementation
  • Integration
  • Testing
  • Deployment

Each of these has a gated exit, such that to exit one phase, you need to meet certain criteria.  For example, to leave "Design" phase, you have to have your detailed design with estimates signed off by developers, analysts, and the customer.  You cannot enter Implementation until you have finished design.

Scrummerfall still uses a phase-based methodology, but uses iterations for the "Design" and "Implementation" phases.  Testing is done as unit tests during development, but QA is not involved until the actual Testing phase later.

Scrummerfall is easier to introduce in companies heavily invested in waterfall, as it's only one group (developers) that are actually changing how they work.

Scrummerfall also makes two assumptions that become more invalid and costly the larger the projects are:

  • Requirements don't change after Design
  • Integration, Testing, and Deployment are best done at the end

Now just because Agile doesn't have gated phases for these activities doesn't mean they don't happen.  Design and requirements gathering still happen, as do release planning, testing, deployment, etc.  The difference is that all of these activities happen each iteration.

This is very tough in fixed-bid projects, which assume that requirements, cost, and deadline don't change.  There are alternatives to fixed-bid projects, which I won't cover here, that provide the best of both fixed-bid and time-and-materials projects.

With Agile, you don't do a "Testing" iteration and a "Design" iteration.  That's lipstick on a pig, you're still doing waterfall. 

So how do you avoid Scrummerfall if you're trying to introduce Agile into your organization?  The trick is to sell the right ideas to all of the folks involved.  If it's only developers leading Agile adoption, chances are you won't get too far past TDD, continuous integration, pair programming, and the rest of the engineering-specific XP practices.

Get buy-in from an analyst, a PM, a tester, your customer, and your developers.  You won't have to convert all of the analysts and PMs, just the ones working on your project.  Remember, each person needs to see tangible business value from the changes you are proposing.  I tend to target management for Scrum and developers on XP, because although it's easy to get everyone to agree on values and principles, the concrete practices vary widely between the different roles.

Tuesday, January 8, 2008

For the record

This is not Scrum:

  • Planning
    • Release planning
    • Backlog creation
    • Architecture and high-level design
  • Development sprints
    • Design
    • Code
    • Test
  • Conclusion
    • System integration
    • System test
    • Release

This is Scrummerfall, where we still do a phase-based waterfall model, but do iterations during the "development" phase.  I hear the word "hybrid" thrown around a lot in the above model.

This isn't the cool kind of hybrid, like a Prius or a Liger (pretty much my favorite animal).  It's more of the Frankenstein hybrid, where it looks good on paper, but in the end you need the village mob with pitchforks and torches to drive it away.  Afterwards, the villagers have a bad taste in their mouth regarding science, so they banish it instead of booting out the mad scientist.

One of the key benefits of agility is the ability to respond to change through feedback.  If the backlog is set in stone before my "development sprints" start, how do I change the backlog once business requirements and priorities change, which they inevitably will?  There is no mechanism to respond to change in Scrummerfall, dooming your project to quick failure, but now you get to blame Scrum.

Another disaster waiting to happen is waiting until the end to do system integration.  I think everyone learned that "it works on my computer" doesn't fly very far once you start collecting a paycheck.  Customers demand the software works on their machine, not yours.  So why wait until the very end to do the riskiest aspect of development, when cost of failure is at its highest?  It pretty much guarantees failure and some exciting blamestorming meetings.

I think these models come about from those who think Agile and Scrum are just another process, a cog to switch out.  Agile isn't a process, it's a culture, a mindset, a belief system, a set of values, principles, and practices.  Treating it like just another process gives rise to tweaking and leads to hideous hybrid Frankenstein monsters, roaming the countryside and spreading failure.

Monday, January 7, 2008

SVN and proxy servers

So I wanted to check out Jeffrey's sample code he demonstrates in the latest dnrTV episode.  I get a fun message back from SVN, which is completely meaningless to me:

It turns out that although SVN works through port 80, the proxy server I'm behind filters HTTP headers, one of which is PROPFIND.  Google tells me that I can configure SVN to use a proxy server, which is what I need to do with several applications (including Live Writer).  Although I have to hard-code my password into the configuration file, it fixes the problem:

I have to change the configuration file every few months when my password expires, but otherwise I'm good.

NBehave source moved to Google Code

Well, we're fed up with it.  CodePlex is a great home for everything...except source control.  We've decided to keep all things project related (wiki, releases, discussions, etc.) on CodePlex, but move our source to Google Code.

We got the inspiration from the MvcContrib project, which is doing the same thing.  Too many people love their SVN, it turns out.  With Google Code, we can use SVN as our SCC provider instead of TFS.  Pulling down source, submitting patches, and other source-related tasks should get much easier.

Our Google Code project can be found here:

http://nbehave.googlecode.com

And the source can be browsed here:

http://nbehave.googlecode.com/svn/trunk/

Our public CCNET instance has been updated, which can be found here:

http://ccnet.nbehave.org/

It's been a bit of a journey integration NSpec and finding a new home for the source code, and moving to SVN should make all of our lives a little easier.

Thursday, January 3, 2008

Application Root is your friend

It still surprises me how many ASP.NET developers I run into don't know about the different ways to construct path references in ASP.NET.  Let's say we want to include an image in our website.  This image is hosted on our website, in an "img" subfolder off of the application root.  So how do we create the image HTML, and what do we use as the URL?  The wrong answer can lead to big-time maintenance headaches later.

There are three kinds of paths we can use:

  • Absolute
  • Relative
  • Application root (ASP.NET only)

Additionally, we have a few choices on how we chose to create the image in our ASP.NET page:

  • Plain ol' HTML
  • HTML server control
  • Web server control

Each kind of path can be used for each rendering object type (HTML, server control).  It turns out that the path is much more important than the rendering object, as different forces might lend me to use controls over HTML.  For posterity, I'll just pick plain ol' HTML as an example.

Absolute

Absolute paths are fully qualified URL paths that include the domain name in the URL:

<img src="http://localhost/EcommApp/img/blarg.jpg" />

Absolute paths work great for external resources outside of my website, but are poor choices for internal resources.  Typically ASP.NET development is done on a development machine, and deployed to a different machine, which means the URLs will most likely change.

For example, the URL above works on my local machine, but breaks when deployed to the server because the "EcommApp" now resides at the root, so I need a URL like "http://ecommapp.com/img/blarg.jpg".  Since this absolute path is different, my link breaks, and I have to make lots of changes going back and forth between production and development.  For internal resources, absolute paths won't work.

Relative

Relative paths don't specify the domain name, and come in a few flavors:

  • Site-root relative
  • Current page relative
  • Peer relative

These URL path notations are similar to file path notations.  Each is slightly different and carries its own issues.

Site-root relative

Here's the same img tag used before, now with a site-root relative path:

<img src="/EcommApp/img/blarg.jpg" />

Note the lack of the domain name and the leading slash, that's what makes this a site-root relative path.  These paths are resolved against the current domain, which means I can go from "localhost" to "ecommapp.com" with ease.

Again, the problem I run into is that locally, my app is deployed off of an "EcommApp" folder, but on the server, it's deployed at the root.  My image breaks again, so site-root relative paths aren't a great choice, either.

Current page relative

Now the img tag using a current page relative path:

<img src="img/blarg.jpg" />

This time, I don't have the leading slash, nor do I include the "EcommApp" folder.  This is because current page relative paths are constructed off the URL being requested, which in this case is the "default.aspx" page at the root of the application.  The request goes from the "default.aspx" path, wherever that might be.  Now my URL does not have to change when I deploy to production, it works in both places.

But I have two problems now:

  • Moving the page means I have to change all of the resource URLs
  • Creating a page in a subfolder means all URLs to the same resource could be different

This leads me to the last kind of relative path.

Peer relative

Suppose I want to create the img tag in a site with the following structure:

  • \Root
    • \img
      • blarg.jpg
    • \products
      • default.aspx

Note that default.aspx has to go up one node, then down one node to reference the file in the above tree.  Here's the img tag to do just that:

<img src="../img/blarg.jpg" />

Similar to folder paths, I use the ".." operator to climb up one node in the path, then specify the rest of the path.  This path works just fine in production and development, but I still have two main problems:

  • URLs to the same resource are different depending on depth of the source file in the tree
  • Moving a resource forces me to manually fix the relative paths

If I decide to move the "default.aspx" page up one level, all of the relative paths must be manually fixed.

But there's one more major issue.

User controls

Now let's suppose I have the following setup:

  • \Root
    • \img
      • blarg.jpg
    • \products
      • default.aspx
    • \user
      • login.aspx
    • \support
      • help.aspx
    • \usercontrols
      • header.ascx
    • default.aspx

All of the ASPX files use the same "header.ascx" control (I'm not using master pages on this site).  The "header.ascx" control needs to reference the img, but note that the relative path is calculated based on the page requested, not the user control requested.  This means that the relative URL will only work if the user control just happens to be included in a page at the correct depth.  All other times it will break, and this is a huge problem.

Luckily, ASP.NET includes a handy way to fix all of these problems, deployment and otherwise.

Application root

A path built with an application root is prefixed with a tilde (~).  For example, here's a raw application path to the image:

~/img/blarg.jpg

Note the "~/" at the front, that's what signifies it as an application root path.  Application root paths are constructed starting at the root of the application.  For example, both "http://ecommapp.com" and "http://localhost/EcommApp" are application roots, so I don't have to worry about changing paths at deployment.

Additionally, I don't have to worry about problems with node depth in the hierarchy, as paths are formed from the root and not relative to a leaf node, so my user control problem disappears.

One issue with application root paths is only ASP.NET knows about them.  Not browsers.  If I do this:

<img src="~/img/blarg.jpg" />

The image breaks, as browsers don't know what IIS applications are, they just know URLs.  ASP.NET, however, will take this URL and generate the correct relative path for you, as long as I use ASP.NET to generate the path.  Server controls, like "asp:hyperlink" can handle the application root path.

To use the application root path in raw HTML, I just need to use the ResolveUrl method, which is included in the Control class, and therefore available in both my Page and UserControl classes.  Combining raw HTML and the ResolveUrl method, I get:

<img src="<%= ResolveUrl("~/img/blarg.jpg") %>" />

The "<%= %>" construct is basically a "Response.Write", and allows me to call the ResolveUrl method directly.

Using application root paths allows me to:

  • Develop locally and deploy to production seamlessly
  • Have consistent URL per resource
  • Use raw HTML without the problems of absolute and relative paths

Some caveats

No matter what I do, I have to change code if either the resource or the page moves.  I can minimize the number of changes by externalizing the specific path (the "~/img/blarg.jpg" part) to a resource file, constant, or static global variable.  This applies for all types of paths, so I like to eliminate as much duplication as possible.

It's dangerous to assume that the structure or names of resources and pages won't change at some point.  As a web site grows, it can become necessary to move resources around and reorganize your site structure.  To minimize the impact of deployment and change, use application paths as much as possible, you'll save on Excedrin later.

Time expired, still going strong

My Live Writer beta expired at the beginning of the year, but I'm still going strong:

I don't see the "Ask Me.....Never" button, so I'll just click the Later button.  It's still less work to click a button once a day than it is jumping through the hoops to get Live Writer installed on a Server 2003 machine.  I still love the LW, so I'll keep clicking away.

Wednesday, January 2, 2008

Targeting multiple environments through NAnt

One of the nice things about using a command-line local build is that I can easily target multiple environments.  Our configuration scheme is fairly straightforward, with all changes limited to one "web.config" file.

When I refer to multiple environments, I'm talking about many individual isolated deployment targets, such as production, integration, developer, local, etc.  Each environment has its own database, services, maybe even domain.  Sometimes I need to configure my local code to point to different environments, where maybe a defect shows up in production but not our integration environment.

A typical scenario might be that I have different database in each environment.  Different databases means different connection strings, and my connection strings are stored in my "web.config" file.  The problem is that the "web.config" file is stored in source control, and I don't want to always check-in and check-out the file each time I want to target a different environment.

Additionally, I don't want to have to remember the connection string when I switch to a different environment.  I want it all automated, and I want it to just work.

To point our local codebase at different environments, we apply a few tricks to NAnt to make it easy to switch back and forth between many environments.

The command-line build

The first item we have set up is a command-line build and local deployment.  Our environment is a too complex to have only solution compilation to be sufficient to actually run our app, so we use NAnt to build and run our software.  To do this, I have a very simple "go.bat" batch file that calls NAnt with the appropriate command-line arguments:

@tools\nant\NAnt.exe -buildfile:NBehave.build %*

When I call NAnt from the command-line, I can pass in multiple targets without needing to specify the build file or other arguments every time:

go clean test deploy

Now that I can easily call different targets in the build, I can use that mechanism to target different environments, doing something like this:

go PROD clean test deploy

Configuring NAnt

To get a NAnt target to change my configuration, I need a few elements in place:

  • File to hold configuration entries
  • Target to load configuration
  • Tasks to apply configuration

The basic idea is that the "PROD" or "SIT" or "DEV" target will load up specific configuration properties.  After compilation, these configuration properties will be inserted back into the web.config file.  I will have a set of configuration properties for each environment that have the same name, but different values.

Configuration settings file

I like to keep my configuration settings in a separate build file, so I created an "environmentSettings.build" file to hold all of the settings for each environment:

<?xml version="1.0" encoding="utf-8"?>
<project name="Environment Settings" xmlns="http://nant.sf.net/schemas/nant.xsd">

  <target name="config-settings-PROD">
    <property name="connection_string" value="Data Source=prddbsvr;Initial Catalog=AdventureWorks;Integrated Security=true" />
  </target>

  <target name="config-settings-SIT">
    <property name="connection_string" value="Data Source=sitdbsvr;Initial Catalog=AdventureWorks;Integrated Security=true" />
  </target>

  <target name="config-settings-DEV">
    <property name="connection_string" value="Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=true" />
  </target>

</project>

Two important items to note are:

  • Target names differ only by last part, the target environment
  • Targets all define the same property, namely "connection_string", but these values are different in each example

Selecting configuration

Now that my configuration settings file is finished, it's time to turn our attention back to the main build script file.  I need to add targets to handle "PROD", "SIT", etc.  Additionally, I want to define a property that has a default environment setting.

The targets that handle "PROD", etc. don't need to do much other than re-define the environment setting property and load the targets from the new file.  Here are those targets:

<property name="target-env" value="DEV" />

<target name="DEV">
  <property name="target-env" value="DEV" />
  <call target="load-config-settings" />
</target>

<target name="SIT">
  <property name="target-env" value="SIT" />
  <call target="load-config-settings" />
</target>

<target name="PROD">
  <property name="target-env" value="PROD" />
  <call target="load-config-settings" />
</target>

<target name="load-config-settings" unless="${target::has-executed('load-config-settings')}">
  <include buildfile="${env-settings.file}" />
</target>

The first thing to note here is the declaration of the "target-env" property at the top.  That will be useful later on when making decisions based on the target environment.

Next, I declare a set of targets named after my target environments, namely "DEV", "SIT" and "PROD".  These are also the same names as the postfixes in the target names in my "environmentSettings.build" file I created earlier.  In each of these targets, I override the "target-env" property with its new value, the target environment.  Remember that in my "go.bat" file, all command-line arguments are targets to be executed by NAnt, so I have to create a specific target for each target environment I want to support.

Finally, I call the "load-config-settings" target.  Its responsibility is simply to load the environment settings build file I created earlier, but not to call any of its targets.  The reason for the "unless" part is that NAnt does not allow you to declare the same targets twice, so I need to make sure that the "load-config-settings" target is only executed at most once.

Loading and applying configuration

Now that I have all of the targets loaded, I need to call the appropriate settings target and apply the configuration properties to the web.config file.  This step is usually done post-compilation, but I can apply the settings any time after they are loaded:

<target name="modify-web-config">
  
  <call target="config-settings-${target-env}" />

  <xmlpoke
    file="${deploy.dir}/Web.Config"
    xpath="/configuration/appSettings/add[@key='ConnectionString']/@value"
    value="${connection_string}"
   />

</target>

First, this target calls "config-settings-XXXXX", where the last part is filled in by the "target-env" property declared earlier.  If I chose "SIT", the "config-settings-SIT" target is called.  If I chose "PROD", the "config-settings-PROD" target is called.  Recall also that the "config-settings-XXXX" targets all declare the same properties, but with different values.

Finally, I use the xmlpoke task to modify the web.config file, giving it the new "connection_string" property value set up from the "config-settings-XXXX" target.

Now, if I want to target different environments, all I need to do is put in the environment name when calling the batch script, such as "go SIT deploy-local", and my local app now targets a different environment.  If there are more complex things I need to do based on the target environment, all I need to do is check the "target-env" property.

Wrapping it up

There are many different ways to target different environments, such as web deployment projects and solution configuration.  I found using NAnt integrated well with our command-line build and gave us a maintainable solution, as all build/deployment logic is hosted in one build script, instead of spread over many project or solution configurations.

Thursday, December 20, 2007

Upgrading to Windows XP SP2

After months of soul-searching, I made the gut-wrenching decision today to upgrade my home PC to Windows XP SP2.

Upgrade from Vista, that is.

I'm completely convinced that Vista is not designed to run on single-core/processor machines.  I've run Vista on work machines without any hiccups, with Aero Glass going full on.  I thought I had a semi-decent home PC:

  • AMD Athlon XP 2800+
  • 2 GB RAM

Alas, it was not enough to net me more than about 2.9 on the Windows Experience Index.  UAC annoys the hell out of me, most file operations take forever, I'm denied access to do simple operations, like creating a folder on my D: drive.  At work, I'll turn all of these safety features off, as I'm okay running with scissors in a development environment.  I have no idea how a home user deals with all of it, I sure couldn't.  Hopefully Vista's SP1 will fix these issues.

Tuesday, December 18, 2007

Extension methods and primitive obsession

In another water-cooler argument today, a couple of coworkers didn't like my extension method example.  One main problem is that it violates instance semantics, where you expect that a method call off an instance won't work if the instance is null.  However, extension methods break that convention, leading the developer to question every method call and wonder if it's an extension method or not.  For example, you can run into these types of scenarios:

string nullString = null;

bool isNull = nullString.IsNullOrEmpty();

In normal circumstances, the call to IsNullOrEmpty would throw a NullReferenceException.  Since we're using an extension method, we leave it up to the developer of the extension method to determine what to do with null references.

Since there's no way to describe to the user of the API whether or not the extension method handles nulls, or how it handles null references, this can lead to quite a bit of confusion to clients of that API, or later, those maintaining code using extension methods.

In addition to problems with dealing with null references (which Elton pointed out, could be better handled with design-by-contract), some examples of extension methods online propose examples that show more than a whiff of the "Primitive Obsession" code smell:

Dealing with primitive obsession

In both of the examples above (Scott cites David's example), an extension method is used to determine if a string is an email:

string email = txtEmailAddress.Text;

if (! email.IsValidEmailAddress())
{
    // oh noes!
}

It's something I've done a hundred times, taking raw text from user input and performing some validation to make sure it's the "right" kind of string I want.  But where do you stop with validation?  Do you assume all throughout the application that this string is the correct kind of string, or do you duplicate the validation?

An alternative approach is accept that classes are your friend, and create a small class to represent your "special" primitive.  Convert back and forth at the boundaries between your system and customer-facing layers.  Here's the new Email class:

public class Email
{
    private readonly string _value;
    private static readonly Regex _regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");

    public Email(string value)
    {
        if (!_regex.IsMatch(value))
            throw new ArgumentException("Invalid email format.", "value");

        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }

    public static implicit operator string(Email email)
    {
        return email.Value;
    }

    public static explicit operator Email(string value)
    {
        return new Email(value);
    }

    public static Email Parse(string email)
    {
        if (email == null)
            throw new ArgumentNullException("email");

        Email result = null;

        if (!TryParse(email, out result))
            throw new FormatException("Invalid email format.");

        return result;
    }

    public static bool TryParse(string email, out Email result)
    {
        if (!_regex.IsMatch(email))
        {
            result = null;
            return false;
        }

        result = new Email(email);
        return true;
    }
}

I do a few things to make it easy on developers to use an email class that can play well with strings as well as other use cases:

  • Made Email immutable
  • Defined conversion operators to and from string
  • Added the Try-Parse pattern

The usage of the Email class closely resembles usage for other string-friendly types, such as DateTime:

string inputEmail = txtEmailAddress.Text;

Email email;

if (! Email.TryParse(inputEmail, out email))
{
    // oh noes!
}

txtEmailAddress.Text = email;

Now I can go back and forth from strings and my Email class, plus I provided a way to convert without throwing exceptions.  This looks very similar to code dealing with textual date representations.

Yes, but

The final Email class takes more code to write than the original extension method.  However, now that we have a single class that plays nice with primitives, additional Email behavior has a nice home.  With a class in place, I can now model more expressive emails, such as ones that include names like "Ricky Bobby <ricky.bobby@rb.com>".  Once the home is created, behavior can start moving in.  Otherwise, validation would be sprinkled throughout the system at each user boundary, such as importing data, GUIs, etc.

If you find yourself adding logic to primitives to the point of obsession, it's a strong indicator you're suffering from primitive obsession and a nice, small, specialized class can help eliminate a lot of the duplication primitive obsession tends to create.

Dead Google Calendar gadget

This morning I received an interesting yet disturbing message on the Google Calendar gadget on my iGoogle home page:

Great gadget that it was, I think I might be a little more discerning about what gadgets I put on the home page.  Word of warning, you probably don't want to google "donkey-punching", definitely NSFW.  It looks like Google changed something, broke the gadget, and the gadget author decided to let everyone know, through an....interesting means.

ALT.NET summary blog

If the ALT.NET mailing list is too much to keep up with, as it is the Mother of All Firehoses (MOAF), several folks have pointed out a nice summary blog:

Alt.Net Pursefight!

It keeps a nice daily ego check and blow-by-blow commentary of some of the more interesting comment wars going on there.  Pretty funny.

Friday, December 14, 2007

Ruby-style Array methods in C# 3.0

A while back I played with Ruby-style loops in C# 3.0.  This sparked my jealousy of other fun Ruby constructs that I couldn't find in C#, and a couple of them are the "each" and "each_with_index" methods for arrays.  Here's an example, from thinkvitamin.com:

my_vitamins = ['b-12', 'c', 'riboflavin']

my_vitamins.each do |vitamin|
  puts "#{vitamin} is tasty!"
end
=> b-12 is tasty!
=> c is tasty!
=> riboflavin is tasty!

With both Arrays and List<T> in .NET, this is already possible: 

string[] myVitamins = {"b-12", "c", "riboflavin"};

Array.ForEach(myVitamins,
    (vitamin) =>
    {
        Console.WriteLine("{0} is tasty", vitamin);
    }
);

var myOtherVitamins = new List<string>() { "b-12", "c", "riboflavin" };

myOtherVitamins.ForEach(
    (vitamin) =>
    {
        Console.WriteLine("{0} is very tasty", vitamin);
    }
);

There are a few problems with these implementations, however:

  • Inconsistent between types
  • IEnumerable<T> left out
  • Array has a static method, whereas List<T> is instance
  • Index is unknown

Since T[] implicitly implements IEnumerable<T>, we can create a simple extension method to handle any case.

Without index

I still like the "Do" keyword in Ruby to signify the start of a block, and I'm not a fan of the readability (or "solubility", whatever) of the "ForEach" method.  Instead, I'll borrow from the loop-style syntax I created in the previous post that uses a "Do" method:

myVitamins.Each().Do(
    (vitamin) =>
    {
        Console.WriteLine("{0} is tasty", vitamin);
    }
);

To accomplish this, I'll need something to add the "Each" method, and something to provide the "Do" method.  Here's what I came up with:

public static class RubyArrayExtensions
{
    public class EachIterator<T>
    {
        private readonly IEnumerable<T> values;

        internal EachIterator(IEnumerable<T> values)
        {
            this.values = values;
        }

        public void Do(Action<T> action)
        {
            foreach (var item in values)
            {
                action(item);
            }
        }
    }

    public static EachIterator<T> Each<T>(this IEnumerable<T> values)
    {
        return new EachIterator<T>(values);
    }
}

The "Each" generic method is an extension method that extends anything that implements IEnumerable<T>, which includes arrays, List<T>, and many others.  IEnumerable<T> is ripe for extension, as .NET 3.5 introduced dozens of extension methods for it in the System.Linq.Enumerable class.  With these changes, I now have a consistent mechanism to perform an action against an array or list of items:

string[] myVitamins = { "b-12", "c", "riboflavin" };

myVitamins.Each().Do(
    (vitamin) =>
    {
        Console.WriteLine("{0} is tasty", vitamin);
    }
);

var myOtherVitamins = new List<string>() { "b-12", "c", "riboflavin" };

myOtherVitamins.Each().Do(
    (vitamin) =>
    {
        Console.WriteLine("{0} is very tasty", vitamin);
    }
);

With index

Ruby also has a "each_with_index" method for arrays, and in this case, there aren't any existing methods on System.Array or List<T> to accomplish this.  With extension methods, this is still trivial to accomplish.  I now just include the index whenever executing the callback to the Action<T, int> passed in.  Here's the extension method with the index:

public static class RubyArrayExtensions
{
    public class EachWithIndexIterator<T>
    {
        private readonly IEnumerable<T> values;

        internal EachWithIndexIterator(IEnumerable<T> values)
        {
            this.values = values;
        }

        public void Do(Action<T, int> action)
        {
            int i = 0;
            foreach (var item in values)
            {
                action(item, i++);
            }
        }
    }

    public static EachWithIndexIterator<T> EachWithIndex<T>(this IEnumerable<T> values)
    {
        return new EachWithIndexIterator<T>(values);
    }
}

The only difference here is I keep track of an index to send back to the delegate passed in from the client side, which now looks like this:

string[] myVitamins = { "b-12", "c", "riboflavin" };

myVitamins.EachWithIndex().Do(
    (vitamin, index) =>
    {
        Console.WriteLine("{0} cheers for {1}!", index, vitamin);
    }
);

var myOtherVitamins = new List<string>() { "b-12", "c", "riboflavin" };

myOtherVitamins.EachWithIndex().Do(
    (vitamin, index) =>
    {
        Console.WriteLine("{0} cheers for {1}!", index, vitamin);
    }
);

This now outputs:

0 cheers for b-12!
1 cheers for c!
2 cheers for riboflavin!
0 cheers for b-12!
1 cheers for c!
2 cheers for riboflavin!

Pointless but fun

I don't think I'd ever introduce these into production code, as it's never fun to drop new ways to loop on other's laps.  If anything, it shows how even parentheses can hinder readability, even if the method names themselves read better.

In any case, I now have a simple, unified mechanism to perform an action against any type that implements IEnumerable<T>, which includes arrays and List<T>.

Wednesday, December 12, 2007

Decomposing a book club

Book clubs can be a great way to foster learning and encourage growth on a team.  They aren't always the best avenue for training, which might include:

  • Formal training
  • Industry events
  • Presentations
  • Brown bag lunches
  • etc.

I always enjoyed book clubs because it gave our team a chance to discuss technical topics on a regular basis, sometimes outside of domains we were working on.

Planning a book club

If you're starting a book club for the first time, you might have to just pick a book that everyone might be interested in without specifically asking anyone.  Having the desire to start a book club probably means you already know what deficiencies exist in your team, so you're better equipped to pick a book.

In that case, pick a deficiency and find a great book to study.  It helps if you've read it beforehand so you know what you're getting yourself into.  Book clubs need guidance and leadership during meetings to make sure learning and growth take place, and it's hard to do if the material is new to everyone. 

Software books usually come in two flavors:

  • Design
  • Technology

Examples of design books might be GoF, anything in the Fowler signature series, Pragmatic Programmer, and other books that are design/principle specific but language/technology agnostic.  Technology books are filled with referential material, but not as much guidance on specific subjects like ASP.NET.

Some books I've done book clubs on are:

  • Programming ASP.NET 2.0: Core Reference, Dino Esposito
  • The Pragmatic Programmer, Andrew Hunt and David Thomas
  • Agile Software Development: Principles, Practices and Patterns, Robert C. Martin
  • Framework Design Guidelines, Cwalina and Abrams
  • Working Effectively with Legacy Code, Michael Feathers
  • Refactoring to Patterns, Joshua Kerievsky

As you can see, I'm heavily weighted to "Design" type books, mostly because values, principles, and practices translate well to any new technology.

Book club agenda

After we select a book, we decide on an agenda and schedule.  For internal book clubs, we try to meet once a week at lunch, covering about 30-40 pages a session.  We try to get each book club to end after 10-12 weeks, or about 4 months.  Everyone reads all the material and discusses it at each meeting.  Sometimes we skip chapters if the material isn't relevant or particularly insightful.

Here in the Austin area, we're forming an Austin-wide DDD book club to go over Evans' Domain-Driven Design book.  The first thing I do in determining schedule is to break down the parts and chapters into the number of pages they take up:

I laid out each of the chapters and noted what page they started on, then calculated the part and chapter lengths in separate columns.  Since a single discussion can never cover more than 40 pages in an hour, I used conditional formatting to add bars signifying lengths of the chapter for easier planning.

Chapter length distribution seemed to be all over the place, so I created a distribution chart to see it a little more clearly:

This distribution is interesting, as it shows a fairly random distribution of chapter lengths.  Not Gaussian, not evenly distributed, but a whole bunch of short chapters, a few medium chapters, a few more big chapters, and one off-the chart chapter.  Ideally, I'd have one 40 page chapter per session, but it doesn't always work out that way.

Suggested agendas

Sometimes, especially with the Fowler Signature Series books, the introductory chapters suggest both the important chapters and a suggested study sequence/reading sequence.  This can guide the book club agenda.

In the case of the Evans book, he calls out the "most important" chapters, and says that all others can be read out of order, but are meant to be read in their entirety.  We might flag some chapters as "nice to have" and put them aside, to go back to later if there's time.

The meeting

Book club meetings are meant to be fun, open, inviting, and intellectually appealing.  If someone isn't engaged, they're probably on their laptop or Crack-berry, so keep an eye out for wandering minds.  Asking questions tends to get everyone involved, rather than a chorus of "yeah that makes sense, I agree, echo echo echo".

If you're leading the book club, be prepared to read ahead and have a list of talking points before you go in.  If anything, the book club leader is charged with creating discussion, but not leading discussion.  Talking points tend to enforce focus, so discussions don't wind down tangents or social topics for too long.  "OMG did you see last night's episode of 'Heroes'?" should be kept to a minimum.

Finally, be aware of your audience.  If you're covering a topic new to a lot of folks, you might have to do some additional prodding to make sure everyone feels like they contributed.  Nobody likes to listen to someone else's conversation for an hour (well, almost nobody).

Encouraging self-improvement

Probably the biggest benefit of book clubs and other organic training like brown bags is that they create a culture of self-improvement.  Having the team engaged in book clubs, brown bags, user groups, etc. can set the bar higher when it comes to quality and pride in individual workmanship.  Plus, sometimes companies pay for the lunch, so that's always good, right?

Thursday, December 6, 2007

Don't hide the ugly

I wanted to take some time to highlight the difference between encapsulation and subterfuge.  Just so we're on the same page:

  • Encapsulation: The ability to provide users with a well-defined interface to a set of functions in a way which hides their internal workings.
  • Subterfuge: An artifice or expedient used to evade a rule, escape a consequence, hide something, etc.

When related to code, both of these techniques hide internal details of the system.  The key difference is who we're hiding the details from.  With encapsulation, we're hiding details from end-users or consumers of our API, which is a good thing.  With subterfuge, we're hiding ugly from developers needing to change the API, which can be disastrous.

Subterfuge hides the ugly, and for ugly to get fixed, I want it front and center.  Subterfuge comes in many varieties, but all achieve the same end result of hiding the ugly instead of fixing the ugly.

Region directives

Region directives in C# and VB.Net let you declare a region of code that can be collapsed or hidden.  I've used them in the past to partition a class based on visibility or structure, so I'll have a ".ctor" region or maybe a "Public Members" region.  Other regions can be collapsed so I don't need to look at them.

For example, our DataGateway class seems nice and concise, and it looks like it has only about 10-20 lines of code:

One small problem, note the region "Legacy db access code".  By applying a region to some nasty code, I've hidden the ugliness away from the developer who otherwise might think it was a problem.  The developer doesn't know about the problem, as I've collapsed over 5000 lines of code into one small block.

If a class is big and nasty, then just let it all hang out.  If it's really bothersome, extract the bad code into a different class.  At least you'll have separation between ugly and nice.  Hiding ugly code in region directives doesn't encourage anyone to fix it, and it tends to deceive those glancing at a class how crazy it might be underneath.

One type per file, please

Nothing irks me more than looking at a solution in the solution explorer, seeing a relatively small number of files, and then realizing that each file has a zillion types.  A file called "DataGateway.cs" hides all sorts of nuttiness:

public enum DataGatewayType
{

}

public abstract class DataGateway
{
    public abstract int[] GetCustomerIDs();
}

public class SqlDataGateway : DataGateway
{
    public override int[] GetCustomerIDs()
    {
        // sproc's for all!!!

        return new int[] { };
    }
}

public class OracleDataGateway : DataGateway
{
    public override int[] GetCustomerIDs()
    {
        // now we're getting enterprise-y 

        return new int[] { };
    }
}

public class MySqlGateway : DataGateway
{
    public override int[] GetCustomerIDs()
    {
        // we don't support hippies 

        return null;
    }
}

Java, as I understand it, has a strict convention of one type per file.  I really like that convention (if I'm correct), as it forces the developer to match their file structure to their package (assembly) structure.  No such luck in .NET, although there may be some FxCop or ReSharper rules to generate warnings.

The problem with combining multiple types to one file is that it makes it very difficult for the developer to gain any understanding of the code they're working with.  Incorrect assumptions start to arise when I see a file name that doesn't match the internal structure.  Some of the rules I use are:

  • One type per file (enum, delegate, class, interface, struct)
  • Project name matches assembly name (or root namespace name)
  • File name matches type name
  • Folder structure matches namespaces
    • i.e. <root>\Security == RootNamespace.Security

With these straightforward rules, a developer can look at the folder structure or the solution explorer and know exactly what types are in the project, how they are organized, and maybe even understand responsibilities and architecture.  Even slight deviations from the above rules can cause unnecessary confusion for developers.  You're not doing anyone any favors by cramming 10 classes into one file, so don't do it.

Letting it all hang out

When I was young, my mom would insist on me cleaning my room once a week (the horror!).  Being the resourceful chap that I was, I found I could get the room resembling clean by cramming everything just out of sight, into the closet, under the bed, even in the bed.  This strategy worked great until I actually needed something I stashed away, and couldn't find it.  I had created the illusion of organization, but the monster was lurking just out of sight.

So instead of hiding the problem, I forced myself to deal with the mess until I cared enough to clean it up.  Eventually this led me to fix problems early and often, so they don't snowball into a disastrous mess.  This wasn't out of self-satisfaction or anything like that, but laziness, as I found it was more work to deal with hidden messes than it was to clean it up in the first place.

If my code is a mess, I'll just let it be ugly.  Ugly gets annoying and ugly gets fixed, but ugly swept under the rug gets overlooked, until it pounces on the next unsuspecting developer.

Monday, December 3, 2007

Dealing with primitive obsession

One code smell I tend to miss a lot is primitive obsession.  Primitives are the building blocks of data in any programming language, such as strings, numbers, booleans, and so on.

Many times, primitives have special meaning, such as phone numbers, zip codes, money, etc.  Nearly every time I encounter these values, they're exposed as simple primitives:

public class Address
{
    public string ZipCode { get; set; }
}

But there are special rules for zip codes, such as they can only be in a couple formats in the US: "12345" or "12345-3467".  This logic is typically captured somewhere away from the "ZipCode" value, and typically duplicated throughout the application.  For some reason, I was averse to creating small objects to hold these values and their simple logic.  I don't really know why, as data objects tend to be highly cohesive and can cut down a lot of duplication.

Beyond what Fowler walks through, I need to add a couple more features to my data object to make it really useful.

Creating the data object

First I'll need to create the data object by following the steps in Fowler's book.  I'll make the ZipCode class a DDD Value Object, and this is what I end up with:

public class Address
{
    public ZipCode ZipCode { get; set; }
}

public class ZipCode
{
    private readonly string _value;

    public ZipCode(string value)
    {
        // perform regex matching to verify XXXXX or XXXXX-XXXX format
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }
}

This is pretty much where Fowler's walkthrough stops.  But there are some issues with this implementation:

  • Now more difficult to deal with Zip in its native format, strings
  • Zip codes used to be easier to display

Both of these issues can be easy to fix with the .NET Framework's casting operators and available overrides.

Cleaning it up

First, I'll override the ToString() method and just output the internal value:

public override string ToString()
{
    return _value;
}

Lots of classes, tools, and frameworks use the ToString method to display the value of an object, and now it will use the internal value of the zip code instead of just outputting the name of the type (which is the default).

Next, I can create some casting operators to go to and from System.String.  Since zip codes are still dealt with mostly as strings in this system, I stuck with string instead of int or some other primitive.  Also, many other countries have different zip code formats, so I stayed with strings.  Here are the cast operators, both implicit and explicit:

public static implicit operator string(ZipCode zipCode)
{
    return zipCode.Value;
}

public static explicit operator ZipCode(string value)
{
    return new ZipCode(value);
}

I prefer explicit operators when converting from primitives, and implicit operators when converting to primitives.  FDG guidelines for conversion operators are:

DO NOT provide a conversion operator if such conversion is not clearly expected by the end users.

DO NOT define conversion operators outside of a type's domain.

DO NOT provide an implicit conversion if the conversion is potentially lossy.

DO NOT throw exceptions from implicit casts.

DO throw System.InvalidCastException if a call to a cast operator results in lossy conversion and the contract of the operator does not allow lossy conversions.

I meet all of these guidelines, so I think this implementation will work.

End result

Usability with the changed ZipCode class is much improved now:

Address address = new Address();

address.ZipCode = new ZipCode("12345"); // constructor
address.ZipCode = (ZipCode) "12345"; // explicit operator

string zip = address.ZipCode; // implicit operator

Console.WriteLine("ZipCode: {0}", address.ZipCode); // ToString method

Basically, my ZipCode class now "plays nice" with strings and code that expects strings.

With any hurdles out of the way for using simple data objects, I can eliminate a lot of duplication and scattered logic by creating small, specialized classes for all of the special primitives in my app.

Time is running out

I popped open Windows Live Writer today and got a fun message:

I thought this product was free, and I never paid for anything, so I'm a little confused how a free product can expire.  Live Writer isn't supported on Server 2003, which is what I use, so I have to jump through 80 or so hoops to get Live Writer installed on Server 2003.  Everything works perfectly fine, but now it seems I will be compelled to jump through the same hoops to upgrade to a version I don't need.  Fun times.

Thursday, November 29, 2007

Hall of shame

We keep a "Hall of Shame" of WTF-level code snippets to remind us that however bad we might think things get, it could always be worse.  It also serves as a reminder to us that we can't be complacent with ignorance, and lack of strong technical leadership in critical applications can have far-reaching negative consequences.  Here are a few fun examples.

Runtime obsolescence

I've seen this when we have members that we don't want anyone to use anymore.  Unfortunately, it didn't quite come out right:

public static bool Authenticate(string username, string password)
{
    throw new Exception("I'm obsolete, don't call me, bro!");
}

Nobody knows not to call this method until their codebase actually executes this code at runtime, which could be at any phase in development.  If it's an obscure method, it might not get called at all until production deployment if test coverage is low.

We want to communicate to developers at compile-time that members are obsolete, and we can do this we the ObsoleteAttribute:

[Obsolete("Please use the SessionContext class instead.", true)]
public static bool Authenticate(string username, string password)
{
}

Both the IDE and compilers support this attribute to give feedback to developers when a member should no longer be used.

Exception paranoia

I've seen exception paranoia mostly when developers don't have a thorough understanding of the .NET Framework.  A try...catch block is placed around code that can absolutely never fail, but juuuuuust in case it does:

public static MyIdentity Ident
{
    get
    {
        if (((HttpContext.Current != null) && (HttpContext.Current.User != null)) && (HttpContext.Current.User.Identity != null))
        {
            try
            {
                return (HttpContext.Current.User.Identity as MyIdentity);
            }
            catch (Exception exception)
            {
                ExceptionManager.Publish(exception);
                return null;
            }
        }
        return null;
    }
}

This is also another case of TCPS.  The "if" block already takes care of any failures of the "try" block, and as we're using the "as" operator, the downcasting can never fail either.  The 13 lines of code above were reduced to only one:

public static MyIdentity Ident
{
    get
    {
        return HttpContext.Current.User.Identity as MyIdentity;
    }
}

If HttpContext.Current is null, I'd rather throw the exception, as my ASP.NET app probably won't work without ASP.NET up and running.

Clever debug switches

This is probably my favorite Hall of Shame example.  So much so that we named an award at my previous employer after the pattern.  Sometimes I like to insert a block of code for debugging purposes.  If I want my debug statements to live on in source control, I have a variety of means to do so, including compiler directives, the ConditionalAttribute, or even source control to look at history.  A not-so-clever approach we found was:

public void SubmitForm()
{
    if (false)
    {
        MessageBox.Show("Submit button was clicked.");
    }
}

To make the code run, you change the block to "if (true)".  This had us cracking up so much we named our Hall of Shame award after it, calling it the "If False Award".  Whenever we found especially heinous or corner-cutting code, they deserved the "If False Award".  We never awarded ignorance, only laziness.

Opportunities to improve

It's easy to let a "Hall of Shame" create negative and unconstructive views towards the codebase.  We always used it as a teaching tool to show that we would fix ignorance, but we would not tolerate laziness.

Every developer starts their career writing bad code.  Unfortunately, some never stop.