Opalescent Dependencies

There are two modes when working on objects having what Scott Bellware calls “Transparent Dependencies.” Check it out right now. In Design/TDD Mode you will want to mock up the dependencies and feed them into the constructor of the class under test, like so (using Rhino Mocks here):

private MockRepository _mocks = new MockRepository();

[Test]
public void CreditCheckService_ShouldDenyCreditToCustomersWithLessThan600PointScore
{
   ICreditCheckServiceAgent mockAgent = _mocks.CreateMock<ICreditCheckServiceAgent>();
   PocoCustomerEntity stubCustomer = _mocks.Stub<PocoCustomerEntity>();

   using (_mocks.Record())
   {
       SetupResult.For(stubCustomer.ID).PropertyBehavior().Return(42);
       Expect.Call(mockAgent.ObtainScore(42)).Return(599);
       LastCall.IgnoreArguments();
   }

   using (_mocks.Playback()
   {
       CreditCheckService theUnit = new CreditCheckService(mockAgent);
       Assert.IsFalse(theUnit.GrantCustomerCredit(stubCustomer));
   }
}

In this wee code fragment we see our unit (class under test, system under test, etc.) is the CreditCheckService. It takes, as a dependency in its constructor, a ICreditCheckServiceAgent interface who is responsible for calling out to an outside service. Imagine a DunsCreditCheckServiceAgent implementation.

Sidebar: note the name of the test method. I like to name my test methods with long names that typically begin with “Should”. That sentence should express some behavior of the unit and be understandable by a business folks and developers alike.

So, again, Scott does a fine job of describing the benefit of the fundamental approach of lifting your dependencies in to the constructor so that mocks can be fed in for testing purposes. This is the bread and butter of TDD. Imagine, though, in a realistic scenario you have a class with loads and loads of dependencies. What then Mr. TDD? Doesn’t my Consumer Coding Mode (our second mode) become cumbersome and tedious to write? Dependency Injection containers to the rescue! Using a DI/IoC container the syntax of the consumer code stays very clean:

CreditCheckService service = IoC.Resolve<CreditCheckService>();

The idea here is that the Inversion of Control container will build up or resolve the object for you based on some configuration. It’s been told that when it finds a constructor parameter of this type or that or a setter property of a certain type to go ahead, create or resolve that type and shove in the dependency. You get two main benefits here: one the dependency resolution rules are (potentially) external to the binary and your code remains concise, terse.  It should be mentioned that I’m using in my IoC example Ayende’s IoC-service-locator thing which I think is pretty slick. I’ll also point you to Aaron and Jacob’s rather cool AutoMocking container thing as a short-hand way of saying DI can help out in “test mode” too.

The Suspension of Test-Driven Disbelief

I tend to see the Test- and Behavior-Driven Development conversion process with all of the “aha! moments” along the way of as very akin to an act of faith: a trust fall.

Remember the scene from Indiana Jones and the Last Crusade when Indy, just prior to entering the Grail chamber, comes to a seemingly impassable subterranean chasm? He realizes the nature of the test (act of faith), closes his eyes, puts one foot forward, and takes the plunge. Of course, our hero doesn’t plummet to his death; he finds himself suspended on a cleverly camouflaged bridge (damn those medieval engineers were good). The path was there the whole time.

So, okay, how is TDD like this? Properly installing it into your daily repertoire requires forming a habit. Doing primarily interaction-based, BDD-style testing requires taking that step into the unknown. Sure you can take the recommendations of others, but until you will yourself to make the move, until your foot actually hits that nigh-invisible bridge, you won’t be sure of your footing.

Wikipedia defines suspension of disbelief as:

Suspension of disbelief… refers to the alleged willingness of a reader or viewer to accept as true the premises of a work of fiction, even if they are fantastic, impossible, or contradictory. It also refers to the willingness of the audience to overlook the limitations of a medium, so that these do not interfere with the acceptance of those premises.

This concept, at least in spirit as we’re not dealing with fiction here, is a necessary precondition to sticking with and getting success from proper TDD. It may seem a strange and backward way of doing things and the Unit Tests that come out of the BDD style will look just plain strange compared to the state-based and assertion heavy style you might be used to. It’s repeating Indy’s first step dozens of times and gaining a bit of confidence each time.

One of these steps inevitably comes when you’re trucking along in the Red-Green-Refactor cycle, mocking this collaborator and stubbing that collaborator and you notice: “Hey, there are interfaces without implementation! How can I run/debug my project?”

Check your disbelief at the door, stay in the cycle, and wait for the payoff. A bit further down the path, when you’ve finished the story and tests are passing, you’ll all of a sudden have a working, shippable, F5-able feature without ever having hit the debugger. Realizing this for the first time ought to bring a smile to your face that rivals any popcorn movie.

The Smart DTO

A Data Transfer Object, DTO, is a very simple data-only object typically used for marshalling data across some kind of boundary in your app. A good DTO consists solely of public fields or read/write properties and is Serializable for what should be obvious reasons. Most people seem to gravitate toward read/write properties. I don’t really have an opinion on the matter. While it’s not really important whether or not that boundary lives on another server or AppDomain those are typically the boundaries that require DTOs. WCF calls them DataContracts.

Smart You Say?

I know, “Smart” and “DTO” don’t seem to belong together. Isn’t a DTO just for data transport? Shouldn’t I limit my DTOs to one mission and purpose in life? Yes and no. While you should keep the DTO simple and limited to a single responsibility, I’m a fan of something I’ve been calling a “Smart DTO.” A Smart DTO is a lot like the a Plain Old DTO (PODTO? POD? Nah.) only it adds a few features that the consumer of your DTO can leverage if it wants too. Data Binding and declarative validation are excellent candidates. (Even though I’m using the term Smart DTO you will, I hope, recognize that I’m still keeping things fairly dumb.)

Data Binding

There is a tiny bit of efficiency you can gain by defining a base class that provides the basic infrastructure needed for data binding in .NET. I say tiny because it only saves you from a few lines of code, but, hey, every little bit counts right?

public abstract class SmartDTO : INotifyPropertyChanged
{
   public SmartDTO() {}

   public event PropertyChangedEventHandler PropertyChanged;

   protected virtual void OnPropertyChanged(string propertyName)
   {
      if (this.PropertyChanged != null)
      {
         PropertyChangedEventArgs args =
            new PropertyChangedEventHandler(propertyName);
         this.PropertyChanged(this, args);
       }
   }
}

In your DTO subclass you’d consume the functionality of the base class like so:

public class PersonDTO : SmartDTO
{
   private string _name;

   public PersonDTO() {}

   public string Name
   {
      get { return _name; }
      set
      {
         _name = value;
         OnPropertyChanged(“Name”);
      }
   }
}

Declarative Validation

Validation is also a convenient thing to put into your Smart DTOs. Specifically I’m talking about the attribute-based implementation of the Martin Fowler’s Notification pattern. I won’t get super specific on this as Jeremy Miller just posted a recipe for implementing this pattern. The DTO above would look like so:

public class PersonDTO : SmartDTO
{
   private string _name;
   private string _email;

   public PersonDTO() {}

   [Required]
   public virtual string Name
   {
      get { return _name; }
      set
      {
         _name = value;
         OnPropertyChanged(“Name”);
      }
   }
   [Required, EmailFormat]
   public virtual string Email
   {
      get { return _email; }
      set
      {
         _email = value;
         OnPropertyChanged(“Email”);
      }

}

DTO Do’s and Don’ts

DO NOT bother with interfaces for your DTOs.

DO define a SmartDTO base class with infrastructure for data binding.

DO use declarative validation on your DTO classes.

DO put your DTOs in a separate assembly and don’t be afraid to distribute that assembly to the consumer IF you own the consumer.

DO NOT rely on the consumer to validate the contents of a DTO.

DO use virtual properties to facilitate using your DTOs with your favorite mocking framework.

DO consider writing a simple Domain-Specific Language for your DTOs. It’s very easy to do and will save a great deal of typing. A simple code generator with a very simple file format will get you to where you need to go, ex:

Class Namespace
Class Name
Property1:Type:Validator1,Validator2,Validator3
PropertyN:Type:Validator1,Validator2,Validator3

MyCompany.MyProduct.DTO
Person
FirstName:string:Required
LastName:string:Required
Ssn:string:Required,SsnFormat
Email:string:Required,EmailFormat

DO NOT confuse the DTO with an Entity (Business Object). Entities model the data and behavior of business constructs that have entities. DTOs model the data of messages. These messages may coincidentally resemble the data modeled in a given Entity.

DO NOT define methods or behaviors on your DTOs. Behavior on a DTO is a good smell that you’re moving expanding past the pattern’s intent and maybe confusing the DTO with the Entities.

DO NOT develop DTOs test-first. In my opinion it’s a complete waste of time and misapplication of the practice. Properly test-driving the design of the Service Layer that consumes/produces the DTOs will ensure they get coverage and the benefit of the test suite safety net.

ReSharper : Developer :: Lightsaber : Jedi

It’s funny to see the universal love of ReSharper that’s in the .NET blogosphere. This strikes me as Sam Gentile has his come-to-Jesus moment with the tool. That kind of made me take note because a) it’s Sam and b) I had the very same experience of starting with CodeRush and Refactor!

Don’t get me wrong I really, really liked the DevExpress tools, they have a lot going for them in terms of UI slickness and the template features are much nicer. Still, I’ve become a ReSharper fan boy.

I heard Aaron and Jacob talking about running both tools and that it took some doing and that they’re also running viemu. These facts, taken in sum, lead me to believe they’re some sort of programming mutants: Exhibit A. I, personally, had to give up on viemu after a week or so. I was never a vi/vim guy but feel like it could boost me up if I just stuck with it.

The (first) hook for me was the source formatting feature (CTRL+ALT+F). What’s nice is that you can setup a whole bunch of rules indicating how you want your code formatted and hit a keystroke and damned if your code doesn’t become the hotness. What struck me is that this feature embeds the XP practice (and general all around good idea) of the code standard (at least the format part of it). More interesting to me is the idea of eventually pushing these values deeper into the tool stack: into languages. Python, for example, enforces a kind of standard through it’s syntactic uniformity and “one way to do it” philosophy.

All of this ReSharper talk makes me want to find some new tricks on my cheat sheet to drill on. I have the sheet pasted under one of my desktop monitors and every day I try to pick up one or two items to focus and drill on. Ilya Ryzhenkov of ReSharper blogs (thanks for bringing this to my attention Maruis) so there’s another way to get a periodic reminder of the depths of the tool. Repetition is key with all of these “knowledge in the head” things.

Still not convinced? Check out this video. Nothing screams developer like the Hackers soundtrack.

Welcome Acropolis

Microsoft’s Acropolis framework purports to help developer build composite smart clients. You know, the kinds of widget-based, dashboard-like applications that were the provenance of CAB and the SCSF.

I crashed a session on this at the MVP Summit. Acropolis looked interesting if not (potentially) indulgent at least for the kinds of product we’re making right now. This kind of framework might work well on the large, especially for financial services / trading desk type applications. I suppose we’ll see if it ignites another debate as did its older brother, CAB.

For more information Don Burnett has a good write up (with pictures!) on his blog.  You can download the CTP here (via Shannon).

It’s the Values, Stupid

The most important part of Martin Fowler’s recent post on the “is Microsoft losing their Alpha Geeks” thread is:

My colleague John Kordyback pointed out that at the heart of all this is realizing that Ruby is not Yet Another .NET Language but a whole community and attitude to software development. Ruby is a community where open source, agile thinking, and lightweight solutions are deeply ingrained values. He says a common problem in Redmond is that “They ask me ‘Why is this language important’ rather than ‘Why is this thinking important?’”

Can anyone argue that Rails, not Ruby, is the real success? It’s a community runtime; it supports the value system of the people. It is not for love of the language. It’s for love of the productive elegance: coding to live over living to code. Jean-Paul Boodhoo’s Building a Solid Core post sums it up A-OK so I won’t harp on when I can just invoke the JP macro (CTRL+J, jp, TAB).

One more thing. I see this notion of “Alpha Geek” as an anathema to the Agile way of life. Can we please drop the Alpha from Alpha Geek?!

In the Canis Lupis social structure there’s always a top dog (actually two, one per sex, but you get my drift). A given gray wolf community has a process in place for enforcing its social contract aimed at increasing survivability or, put in Agile terms, sustainability:

Rank order within a pack is established and maintained through a series of ritualized fights and posturing best described as “ritual bluffing”. Wolves prefer psychological warfare to physical confrontations, meaning that high-ranking status is based more on personality or attitude than on size or physical strength. Rank, who holds it, and how it is enforced varies widely between packs and between individual animals. In large packs full of easygoing wolves, or in a group of juvenile wolves, rank order may shift almost constantly, or even be circular (for instance, animal A dominates animal B, who dominates animal C, who dominates animal A). [Wikipedia]

We, attempting to be civilized creatures, can get our eats at Whole Foods (or the bodega on Loisaida as the case may be) and any competition for genetic dominance can reasonably take place outside of the software development sphere. What works for for the wolf isn’t necessarily what’s good for the cross pollination of ideas, innovations, and view points. I’d argue that the “Alpha” part puts it spot on; people of this ilk often self-identify with the wolf model and it’s really not all that necessary or wanted. See Evan’s recent annoyance with the alpha baditude:

That is, unless you are one of those “jumping ship” to leave MS and all us “Morts” behind.  I won’t be following you.  The .NET jobs are paying really well right now, and most of the self-described “alpha geeks” I’ve met in the wild are a pain-in-the-ass to talk with, let alone work on a team with.  It’s typically either their way or the highway.  They know everything and you suck.  Screw that mentality.  I do hope all the alpha geeks migrate to RoR.  I won’t miss the attitude.

Let’s not forget that Courage and Respect are two of the core values in eXtreme Programming. Have the courage to stand up to the ego-driven alphas. Better yet, demonstrate leadership yourself through respecting and listening to other people around you; you’ll grow yourself that way. Don’t get me wrong, I love a passionate argument, but we can check the Simpsons-Comic-Book-Guy personality disorder at the door!

Dialectics, baby. Dialectics… 

Entity Framework, PI

The latest installment the Entity Framework hullabaloo comes from Danny Simmons and looks like a step in the right direction. He says, “when so many people give such passionate feedback it was clear that I needed to investigate more before I could claim to have any sort of an informed opinion.” I see this as a great example of how participation from the ALT-minded Agilists and OSS folks are leading to change in something that’s likely to get a lot of attention and adoption from the .NET developers in the large.

Jeremy has a list of why he’d want Persistence Ignorance support in an ORM. In addition to the usual suspects of testability and single responsibility I’d need to add the oft-overlooked issue of aesthetics and elegance.

In a truly maintainable system, the code should read as clearly, cleanly, and concisely as possible. Ideally you’d have tests as a prologue (though I find most TDD type tests end up being design artifacts and slightly overhyped as eliminating the need for documentation, more on that later), but the code itself should flow like poetry and be layer cohesive.

By “layer cohesive” I mean if I’m in the a Domain Model project I want the model language — not programming language, the syntax I’m creating out of the general purpose language – to adhere the Ubiquitous Language of the domain I’ve modeled. If I’m in a Services layer project of my app I can afford a few attributes; they become readable as I’ve context-switched into that layer and know what to expect. Danny makes mention of this in supposing they’ll remove the requirement for attribute-based mappings:

At some point we will add an alternative mechanism for specifying metadata about the entity objects (thus freeing us from the hard requirement for attributes).

You know C# is a fine language for OO development (IMHO, the finest though I still want IronRuby for glue and Internal DSLs). As this is the default style of work I’m bringing to bear on problems I’m happy to see Microsoft finally leveraging it in their own frameworks/tools. Sure OO is hard, but I see Astoria as another example of consideration being given to alternative and emerging work styles (RESTful, mashups, etc.). I think the ADO.NET team should be given a great deal of credit engaging with the community and channeling the feedback into deliverable.  

Google’s Sense of Humor

As long on we’re on the subject of tools, I thought this was funny: “Google Gears - These are the gears that power the tubes!” I love it when software has little bits of character in it. It takes me back to an Easter egg in the tips screen of an old version of Office: “You can hurt yourself if you run with scissors.” 

I’m beyond excited to finally offline access to my feed reader of choice. I wonder how this will affect FeedBurner statistics. 

image