Archive for Uncategorized

Playing with BDD: ContextSpecification

So I’ve been messing around today with Behavior Driven Design today (Bellware Driven Design? Or is it Context/Specification?). I thought I’d share my super simple example with you today, and see if anyone wants to claw my eyes out for my obvious inadequacies.

Everyone seems to have a ContextSpecification class, but nobody really seems to think it’s terribly important to say what’s in it. That or they show the code (Thanks JP!) but then it’s missing confusing pieces (What’s a “unit_test_container”? Grr @ JP!).

Maybe it’s obvious to everyone else. That’s ok. It really really wasn’t to me.

I ghetto-rolled a ContextSpecification class for myself on top of NUnit. It probably makes the BDD Mafia want to set fire to my children, but it has worked for me. And when I say it has worked for me, I mean I’ve been using it at least 2 hours now. Here it is:

[TestFixture]
public abstract class ContextSpecification
{
    [SetUp]
    public void SetUp()
    {
        EstablishContext();
        Because();     }

    [TearDown]
    public void TearDown()
    {
        AfterEachSpecification();
    }

    protected abstract void Because();
    protected abstract void EstablishContext();

    protected virtual void AfterEachSpecification()
    {
    }

    protected InterfaceType Dependency<InterfaceType>()
    {
        return MockRepository.GenerateMock<InterfaceType>();
    }

    protected InterfaceType Stub<InterfaceType>()
    {
        return MockRepository.GenerateStub<InterfaceType>();
    }
}

So the SetUp method calls EstablishContext() and Because(). Simple.

I was testing this stupid little PasswordService of mine, so I created a PasswordServiceSpecification that setup some mocking and stubbing using our friend Rhino Mocks 3.5 “Now with extra => operators”.

public abstract class PasswordServiceSpecification : ContextSpecification
{
    protected IPasswordService passwordService;
    protected IPasswordStrengthService passwordStrengthService;
    protected IPasswordHashGenerator passwordHashGenerator;

    protected override void EstablishContext()
    {
        passwordHashGenerator = Stub<IPasswordHashGenerator>();
        passwordHashGenerator.Stub(x => x.CalculatePasswordHash(string.Empty))
            .IgnoreArguments()
            .Return(Password.InvalidPassword);

        passwordStrengthService = Stub<IPasswordStrengthService>();
        passwordStrengthService.Stub(x => x.CheckStrength(string.Empty))
            .IgnoreArguments()
            .Return(PasswordStrength.Strong);

        passwordService = new PasswordService(passwordStrengthService,
            passwordHashGenerator);
    }
}

Ain’t she a beauty? That’s really not terribly important, but I wanted to show it, because I hate it when people assume that I don’t care about some bits of the code. Finally, we have actual specifications.

public class When_setting_a_users_password : PasswordServiceSpecification
{
    private Person user;
    private string newPassword;

    protected override void EstablishContext()
    {
        base.EstablishContext();
        user = Dependency<Person>();
        newPassword = "password";
    }

    protected override void Because()
    {
        passwordService.SetUserPassword(user, newPassword);
    }

    [Test]
    public void Should_check_the_password_strength()
    {
        passwordStrengthService.AssertWasCalled(x => x.CheckStrength(newPassword));
    }
}

I’m told that it’s relatively important for the Because to be a single line of code, and the Tests (Should_*) to be a single line of code. It makes sense to me because if it’s a single line of code then you’re explicitly stating “this thing causes this other thing”.  Of course I don’t want to be too dogmatic about that because I can see that becoming pretty clusterfracky when the Should_* gets complicated.

I have a problem though. I wanted to check and see if an exception is being thrown, so I happily wrote this test:

public class When_setting_the_password_on_a_null_user : PasswordServiceSpecification
{
    private string newPassword;

    protected override void EstablishContext()
    {
        base.EstablishContext();
        newPassword = "password";
    }

    protected override void Because()
    {
        passwordService.SetUserPassword(null, newPassword);
    }

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Should_throw_an_exception()
    {
        // Do Nothing
    }
}

Too bad it doesn’t work for beans. Since the Because() is called by ContextSpecification.SetUp(), the exception is caused before the test is actually run, so the ExpectedException(…) doesn’t catch the exception thrown in the Because(). I didn’t much like the syntax anyway, but I didn’t really know where to go from there.

I briefly forayed into capturing exceptions from Because’s, but then realized that was a horrible idea.

I emailed Jimmy Bogard about it, because he seems smart. He said he might blog a solution to my woes. Wouldn’t that be hot?

PS- Is it weird that I was a little scared to put Bellware’s name in my blog post, for fear of having my face melted off? I’m pretty sure I’m one of the “noname bloggers” though, so I think I’ll be ok.

PPS- Wow this code is really hard to read. I’m sorry about that. Anyone want to recommend a syntax highlighting code snipped plugin for livewriter that plays nicely with WordPress?

Comments (2)

use Lingua::Romana::Perligata;

Lingua::Romana::Perligata, when Perl is just too readable.

#! /usr/local/bin/perl -w

use Lingua::Romana::Perligata;

maximum inquementum tum biguttam egresso scribe.
meo maximo vestibulo perlegamentum da.
da duo tum maximum conscribementa meis listis.

dum listis decapitamentum damentum nexto
    fac sic
        nextum tum novumversum scribe egresso.
        lista sic hoc recidementum nextum cis vannementa da listis.
    cis.

Leave a Comment

Restrict Action to a Particular Type of HttpRequest in Castle MonoRail

This is one of those things that apparently everyone just knows, but I didn’t, and haven’t, for the past 3 months of doing MonoRail development. Color me stupid. Hopefully someone else out there can benefit from this.

If you want to restrict a certain action to only be available via a particular type of http request (POST, GET, etc), all you have to do is add an AccessibleThrough attribute to your action, like so.

[AccessibleThrough(Verb.Post)]
public void Delete(int id)

Yup, that’s it! I started down this path of parsing strings and case insensitive comparisons all the while thinking "This has got to be easier". Turns out it is.

Leave a Comment

FormHelper.Select with Enum

If you’re using Castle Monorail, and trying to use the FormHelper to create a form select janger from an enumerated type, you may or may not be confused as I was.  It’s not obvious, and I couldn’t find many good docs, outside of a forum post.

This is how to do it. First, you have to pass the Enum type into your view data (here: MemberRoles).

public void Edit([ARFetch("mid")] MembershipInformation membership)
        {
            PropertyBag["MemberRoles"] = typeof (MemberRole);
            PropertyBag["membership"] = membership;
        }

Then you have to wrange with FormHelper. I have a love-hate relationship with FormHelper. It can be really frustrating sometimes. Anyway, here’s the syntax for how to make your select statement.

$FormHelper.Select("membership.MemberRole",
    $FormHelper.EnumToPairs($MemberRoles),
    $DictHelper.Create("value=First", "text=Second"))

What FormHelper.EnumToPairs does is create an array of Pair<int, string> objects. The Pair<> object has 2 properties, First, and Second. First, in this case, is an integer with the enum value, Second is a string of the enum’s name. So you pass that bad boy into your FormHelper as the array of select thingies, and then tell it to use the "First" property as the value of the select and the "Second" as the text to display.

Magic!  Painful, painful magic! Maybe I should write my own FormHelper.EnumSelect thing.  Hrmm…

Leave a Comment

StringClob FTL

Found another Castle ActiveRecord/NHibernate gotcha today.

I had string columns being noisily truncated in my ActiveRecord types. Grr. I google and find a solution in the ActiveRecord FAQ: add a ColumnType="StringClob" to the property attribute.

[Property(ColumnType="StringClob")]
public String Contents
{
    get { return _contents; }
    set { _contents = value; }
}

Silly me though, I expected that to actually work as advertised. It doesn’t.

When you use ActiveRecord to create your schema, it will create the above column as a NVARCHAR(255). OMGWTFBBQ?!

The solution is to add an SqlType = "NTEXT" to your attribute as well.  Mmm, cryptic.

[Property(ColumnType = "StringClob", SqlType = "NTEXT")]
public string Description { get; set; }

Please refer to the following for further discussion of the issue.

Comments (3)

Best Books EVAR!

I’ve been wanting to post a list of software engineering books I like, but, while I still may do so, some Jurgen Appelo fellow just posted a pretty good list to start off with, so huzzah for you.

Leave a Comment

Pragmatic Learning

I am not always as pragmatic as I should be. This is mainly due to the fact that I’m a moron.

I was reading this post by Scott Hanselman (his voice is so soothing… almost dreamy…) and I realized that I am not terribly good at being pragmatic. I fall into a pretty big trap I think a lot of us nerdy folk fall into: trying to do things right the first time.

Mr. Hanselman was discussing how his past experienced with Win16/Win32/WinForms/Etc. (Thunking? WTF is thunking? I’m pretty sure I don’t want to know.) clouded his conceptions of how to develop a WPF application. He is well versed in the best practices of those older technologies, but WPF is a pretty new animal, and a lot of those assumptions will not carry over. We have to be willing to accept that fact, otherwise we become an obstacle to our own growth (I love Raganwald).

Hanselman started the WPF project with two goals: get it working, and make it clean. He had a revelation, and reading about his revelation caused a revelation by proxy in myself. Getting it working is the more important goal. Making it clean is the secondary goal.

When you have experience with a technology or technique, I believe these goals can be accomplished simultaneously and with no extra cost; however, when learning a new technology, it is hard to make it clean without knowing the best practices for that given technology. Best practices are hard to learn except through experience. You can read blogs all day and talk to people and debate the pro’s and con’s of different approaches, but really until you get in there and actually taste the code, you won’t be qualified to make a judgement one way or the other for your particular application.

That’s the trap I fall into. When starting a new bit o’ code, I read about how it should be done and spend an inordinate amount of time trying to do it right, when really I should just get it working.

Before you jump down my throat with, "Omgponies! The design! The design!", let me clarify a bit. Making it clean is still a goal. After you get it working, you have to revisit it and make it clean.

Maybe you were lucky and did it right the first time. However, for those of us on Earth, we more than likely noticed friction points while writing our code: places where the code resisted our will. We must subjugate these code modules so that they do our bidding without giving us any lip. We must teach them a lesson through the art of Refactoring as handed down from up on high by Martin Fowler (PBH).

So my new mantra: "I can’t do it right the first time, but it’s ok, because I can fix it later."

Oh and caveat emptor: if you don’t have ReSharper, you can’t reasonably fix it later.

Leave a Comment

The Dark Art of NHibernate

Ok so maybe it’s not a dark art: I just don’t have the book yet. It could be argued the book doesn’t exist yet, but now we’re getting sidetracked.

I was trying to write a DetachedCriteria for a type hierarchy and was stumbling hard. I have 3 classes NationalX, StateX, and OrganizationX that derive from a base type X. X is QualificationType, but I don’t really feel like typing that 50 million times (Does Live Writer needs intellisense?  :) )

I need to pull all X’s with State = state (type: StateX), Organization = organization (type: OrganizationX), and all records of type NationalX.

I got this far and hit a wall. This pulls out all the StateX’s and OrganizationX’s I’m interested in:

DetachedCriteria criteria = DetachedCriteria
     .For(typeof(QualificationType))
     .Add(Expression.Or(
              Expression.Eq("State", state),
              Expression.Eq("Organization", org)
              ));

Great!  I love NHibernate.  But how do I get those damn NationalX’s? There is no unique property in NationalX that is common across all the records I want aside from their type. I did not want to add a type property to my base, that seemed messy and a horrible idea.

Chris Bilson, god love him, saved my bacon. Every NHibernate entity has a Property you can query against, "class", that does pretty much exactly what you think it would.  I still can’t find any docs as to what this magical thing is really called. It’s probably in that damned book I don’t have. This is what I ended up with.

DetachedCriteria criteria = DetachedCriteria
    .For(typeof (QualificationType))
    .Add(Expression.Or(
             Expression.Or(
                 Expression.Eq("State", state),
                 Expression.Eq("class", typeof (NationalQualificationType))),
             Expression.Eq("Organization", org))
    );

This works, And how! I begin the descent into learning NHibernate.  Heaven help me.

PS- Expression.Or() should accept a paramarray.  That’d be hot.

Leave a Comment

NVelocity and Collections (and Possibly Arrays)

I just spent 40 minutes banging my head against a pointy sharp wall. I’m using NVelocity as my view engine on a Monorail project and couldn’t figure out how to access an element of a collection.

$collection[0]          // Doesn't work
$collection(0)          // Nuh-uh
$collection.[0]         // Nope
$collection.get(0)      // As per Velocity Docs.  Nope
$collection.get_Item(0) // THIS WORKS!

Ok, so that’s incredibly not obvious. I couldn’t find any reference to it on the Castle Project Website, the Velocity docs the Castle site refers you to, or pretty much anywhere.  I did find it in the google group though, but only after a lot lot lot of searching. So hopefully this will save someone out there a few minutes of their life.

Or maybe I should just switch to Brail.

Comments (2)

My First Fluent Interface

I think I just wrote a fluent interface. I’m not really a fluent interface expert, so I’ll let you be the judge. But I think it is!fluent-interface-class-diagram

Here’s the gist of the domain problem. Organizations have members. Groups have members. Groups belong to Organizations. Members are Users. *phew*

The requirement that lead to the generation of a fluent interface was that there was a membership requirement on groups. Specifically, users may be members of groups only if they are members of the Organization to which the group belongs. Originally this was expressed as code as an if clause in the method Group.AddMember() like so:

public void AddMember(User user)
{
    if (!this.Organization.Members.Contains(user))
    {
        throw new InvalidOperationException("User does not meet membership requirements for group");
    }
    members.Add(user);
}

This is perfectly fine, but I didn’t like how this Membership Requirement was buried deep in an AddMember() call in the group function. Plus, we’re already talking about how group membership may require the satisfaction of any number of bizarre and yet untold criteria. I put my thinking cap on.

First, let me say that the solution I ended up with isn’t terribly pragmatic. I over-engineered it a bit, but one of the goals of this product is learning, so I’m ok with that.

In my head, what I wanted was something along the lines of this:

if (!MembershipRequirements.AreSatisfiedBy(user))

That was a bit too much to hope for however, as it implies a little bit of an all knowing oracle to know what the hell I’m talking about. I also wanted a solution that would manage Organization membership requirements in the same fashion as Group membership requirements.

This is the syntax I ended up with, and I shall break down how it work after that:

if (!MembershipRequirements.For(this).AreSatisfiedBy(user))

I’m pretty pleased with that. Now here’s how it works:

MembershipRequirements is a Static Gateway whose method For() returns an IMembershipRequirements object.

    public class MembershipRequirements
    {
        public static IMembershipRequirements For(object objectThatRequiresMembershipRequirement)
        {
            return For(objectThatRequiresMembershipRequirement.GetType(),
                       objectThatRequiresMembershipRequirement);
        }

        private static IMembershipRequirements For(Type type, object instance)
        {
            Debug.Assert(type.IsInstanceOfType(instance));

            return DependencyResolver
                .GetImplementationOf<IMembershipRequirementsFactory>()
                .CreateFor(type, instance);
        }
    }

This is heavily inspired (read: stolen) from Mr. Boodhoo. Anyway, you pass into MembershipRequirements.For() the Group or Organization and it returns a MembershipRequirementsFactory implementing IMemberhipRequirementsFactory. The DependencyResolver bit is another static gateway from JP’s blog that I found to be pretty handy. It’s basically just a wrapper for your IoC container (Windsor, in my case).

So MembershipRequirements gets a implementation of IMembershipRequirementsFactory. What is that you ask?  Well it’s pretty stupid.

    public interface IMembershipRequirementsFactory
    {
        IMembershipRequirements CreateFor(Type type, object instance);
    }

And the implementation of this bad boy looks like this:

    public class MembershipRequirementsFactory : IMembershipRequirementsFactory
    {
        public IMembershipRequirements CreateFor(Type type, object instance)
        {
            Debug.Assert(type.IsInstanceOfType(instance));

            if (type == typeof(Group))
            {
                Group group = (Group) instance;
                return new GroupMembershipRequirements(group);
            }

            if (type == typeof(Organization))
            {
                Organization organization = (Organization)instance;
                return new OrganizationMembershipRequirements(organization);
            }

            string errorMessage = String.Format("There exist no Membership Requirements for type {0}", type.FullName);
            throw new InvalidOperationException
                (errorMessage);
        }
    }

Now, truth be told, I’m an idiot. I’m pretty sure there is some more clever way to do this with generics and using all the magic in my IoC container, but I just started with IoC containers last week, so this is what I’ve got so far. I’d be eager to hear any responses.

As an example of what is going on, here is the GroupMembershipRequirements class. Hold on, this mother is hell-of complicated:

    public class GroupMembershipRequirements : IMembershipRequirements
    {
        private Group group;

        public GroupMembershipRequirements(Group group)
        {
            this.group = group;
        }

        public bool AreSatisfiedBy(User user)
        {
            return group.Organization.Members.Contains(user);
        }
    }

Ok, so it’s really simple. You might ask, "You just moved that one line of code from inside Group through 15 layers of abstraction to a new class! Why the hell would you do that?!" And you’d be right. If this is my only membership criteria, then this is pretty lame. But there are more membership criteria on the way, and organization membership criteria are already covered, and well, I’m just learning and this is pretty cool to me.

But come on, this syntax, regardless of whether this is an organization or a group, is hot:

if (MembershipRequirements.For(this).AreSatisfiedBy(user))

The reference to "this" can be *anything* as long as you code the support in for it. It’s almost proper English! I like the syntax, I think the implementation could be made cleaner.

Leave a Comment