Sunday, September 27, 2009

Kickstart your BDD training

Rob Conery posted an excellent quick-start for getting up and running using MSpec titled "Make BDD your BFF". For those who still haven't taken the plunge, MSpec is framework for writing tests using the BDD style of development. Overall, the literature on MSpec on the internet is lacking so take advantage of this and help get the word out!

Also, just so I'm not repeating too much, Apostolis Bekiaris just posted an entry similar to my own except with more links to resources.

Friday, September 25, 2009

I don't mock much anymore

I still use Rhino Mocks. Never tried any other libraries. I probably should just so I can be more worldly but it's fit my needs and I have a laundry list a mile long of ToDos.

That being said, I've done a lot of unmentored exploration into the whole unit test and TDD countryside. At the beginning of my journey I did a metric ton of mock creation. I'm speaking to the different types of test doubles. Go check out Fowler's ever-expanding documentation on the topic.

What I found was the obvious (but not at the time); mocks are part of the test assertions. Its giving me intimate details about how an object is doing its work. As such, they should only be used to verify the test at hand. If they are not truly verifying the expected behavior then it's not a mock. It's a stub, it's a fake, it's something that's allowing the process to emulate its behavior in some integrated environment.

The tests get brittle when you mock things that have no business being mocked. What I started doing was creating everything as a stub and then used the Rhino Mocks AssertWas/WasNotCalled() extension methods. Things end up being much cleaner and far less prone to unexpected test failures.

But I ramble. We're coders. Let's look at some code. Here's an example of a test I wrote using Context/Specification (a style of testing supporting BDD) and the MSpec library. Everything is a stub and I use the AssertWas/WasNotCalled() to assert that certain collaborations occurred the way I had expected them to.

Forgive the user_registration_scenario class as I use it as the base class for a number of scenarios not shown here. It's the collection of inputs/collaborators used for the test and, per Context/Specification, the Act of Arrange/Act/Assert is at a class level, not at a method level.


[Concern(typeof(UserAccountCreationService))]
public class When_a_user_registers_successfully : user_registraton_scenario
{
Establish context = () =>
{
var no_errors = new List<ErrorInfo>();

_modelValidator
.Expect(v => v.Validate(_account))
.Return(no_errors);

_userRepository
.Expect(r => r.UsernameExists(_account.Username))
.Return(false);
};

Because of = () => _service.Create(_account);

It should_send_confirmation_email =()=>
_emailService.AssertWasCalled(es => es.SendConfirmationEmail(_account));

It should_save_user_to_persistent_store =()=>
_userRepository.AssertWasCalled(r => r.CreateUserAccount(_account));
}

public class user_registraton_scenario
{
protected static IEmailService _emailService;
protected static IUserRepository _userRepository;
protected static IModelValidator _modelValidator;
protected static UserAccountCreationService _service;
protected static UserAccount _account;

Establish context = () =>
{
_account = new UserAccount { Username = "kdog" };
_modelValidator = MockRepository.GenerateStub<IModelValidator>();
_emailService = MockRepository.GenerateStub<IEmailService>();
_userRepository = MockRepository.GenerateStub<IUserRepository>();
_service = new UserAccountCreationService(_userRepository, _emailService, _modelValidator);
};
}


I might remark that I'm quite enamored with Context/Specification. I never liked the look of my tests so much. At work, it's agonizing because we're still at a very basic level of unit testing. I'm thinking of giving a presentation on BDD using MSpec...

Sunday, April 12, 2009

Constructor injection FTW

I prefer using constructor injection with DI for a few simple reasons.
  1. It's self-documenting code. It's explicitly telling clients or maintainers of the component how it's put together.
  2. It keeps my components honest. In most cases, excessive constructor arguments is a code smell.
I also don't like setter injection for a few simple reasons.
  1. It adds noise to component's API. I wouldn't want to see public properties hanging off a component that serves's me no use as a client.
  2. It feels like it breaks encapsulation. How the component does its work internally shouldn't be part of its public API.
  3. It obfuscates how the component is put together.

Thursday, April 9, 2009

Finally; ubuntu installs...no problems!

This has been a WIP since years and years now. I install the latest version of Ubuntu two or three times a year mostly because I'm curious and partially because I'm a masochist. I generally want to get into using an open source OS and just be aware of how things work on the other side of the fence (being a Windows user and .NET developer). That's also why I chose Ubuntu; it's the entry-level linux distro.

Things usually work out this way; I install Ubuntu and there are issues. Wireless has never worked out-of-the-box. The graphics are 50-50. Sometimes they work and other times they don't. I've done the whole ndiswrapper thing and iwconfig and messed around on the command line more than any Windows user should ever have to feel comfortable with. Things never end up pretty and are generally unstable.

For instance, my last installation was Ubuntu 8.04. Wireless didn't work. Graphics were fine. I sacrificed the customary chicken and goat and eventually got the wireless to work. But then after I did a restart it stopped working again. Then it intermittently worked until finally it stopped working altogether. Completely random.

I tethered my laptop to the wired network and decided to updgrade Ubuntu to 8.10. After I did, the bootup had the funniest behavior. It would stop booting unless I pressed keys. Nothing in particular. Just pressing keys would make it advance. Once I booted into the desktop it said there were new drivers for the nVidia graphics card. I let the update take place (the drivers were recommended by Ubuntu). When I restarted, I couldn't get to the desktop anymore. One of the startup steps would fail and it would die. I'm not a linux ninja so it was as good as dead.

I burned down the now defunct Ubuntu 8.10 install. I downloaded and installed Kubuntu 8.10 out of sheer desperation. It too demonstrated the "press some goddam keys to boot" behavior so this wasn't an isolated incidence. Once I got to the desktop it didn't recognize I had wireless card at all and the graphics chip wasn't detected either. I was worse off than when I was just in Ubuntu 8.10. Fail.

That was last night. Today, I see that there's ubuntu 9.04 experimental. I installed it, it detected my wireless and it only took a minor spiritual channeling to get the graphics to work. Needless to say, I am happy that things just worked out-of-the-box. This blog post has come from my linux desktop. Joyous day!

Monday, April 6, 2009

Hot feature storm and digging into ASP.NET MVC

Hot feature - A feature that is released as a hotfix usually due to an overly complex or bloated release process that makes normal releases a burden on the entire organization. Those wishing to circumvent the release process will hide features in hotfixes and have them pushed out without any of the normal safety nets used for an official release.

Hi and welcome to my life for the last month. Hot features suck. As a developer, I've never felt so dirty or violated. The things I do for money...

The story; we built a releasable product but never got an official release for it due to lack of QA resources and the overall brutal release process we have now (4 days for the automated QA tests to run! Bullshit!). The solution that was worked out was that I had to tear apart the product and release each feature as a hotfix (henceforth, hot feature). Decomposing a product for its features in a non-chronological order was a nightmare in and of itself given how code evolves. This was only compounded by the fact that there was perfect storm of daily issues that would block or bump these hot features. There was one day where I had to tear apart the product 3 times, each time adding or removing a feature until ultimately, we didn't release anything at all. I will never partake in such a thing ever again.

Tomorrow we push out the last of the hot features and I'll officially be switching teams. My new role is much like my existing role. I'm generally involved with modeling the solution domain and implementing the application layer. One of the first things my team lead has indicated to me is that I'll be working on some new web pages and the platform of choice is going to be ASP.NET MVC. This is thrilling news for me as I've never cut my teeth on any MVC platform. I've been reading about it, I bought a Ruby book that just arrived today so that I could try out rails and I'm hearing stuff all the time from Mr. O'Hara about his MVP framework.

As the .NET web dev world knows, ASP.NET MVC 1.0 was RTM'ed a few weeks back. I've kept it on my radar but hadn't invested any time into it. Not because I don't care but that I've been involved with a brutal release schedule at work (as outlined above) and a newborn child. This last weekend I finally had a chance to download it and take it for a spin.

I've been developing with web forms since time out of mind and I haven't really known anything else. They've never felt quite right and given my gravitation towards TDD, it's become apparent, more than ever, that it's just not the right solution for me. I can't test the way I want to and I have to struggle against web forms to create logic that fits the web forms domain, not my product's domain. I've got the page lifecycle down pat and it was a great introductory solution for me to get acquainted with web app development but it just creates tightly coupled code by default.

My first impression of MVC; I'm smitten. It just flows the way my mental model of the application layer should be behaving. As far as ASP.NET MVC I'm glad I hopped on at 1.0 since they've improved it considerably since the betas. What it allows me to do is nearly forget the fact that I'm working on the web (outside of rendering the views). Controllers create the workflow of the app and they create truly meaningful names and actions that speaks directly to what you're modeling. It's liberating from my years of web forms oppression.

I really want to articulate for all 3 readers in my audience how this has liberated me and one example ran through my mind that captured it perfectly. Let's take the example of some portion of a simple banking application where we want to save a deposit. Use your imagination as to how it should behave.

In web forms, I load an account on Page_Load and I tie into the button click event of a web control to submit a deposit from a user.
public partial class AccountPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Load the account
}

protected void btnSaveDeposit_Click(object sender, EventArgs e)
{
//Save the deposit
}
}

In MVC, I speak to the AccountController and I tell it to load an account or save a deposit.
public class AccountController : Controller
{
public ActionResult LoadAccount(int accountId)
{
//Load an account and show it to the user.
}

public ActionResult Save(Deposit deposit)
{
//Save the deposit
}
}

Do you see the difference in the way you think about this code? Web forms have the unintentional side effect of obfuscating the workflow of your application. It's noise that doesn't speak to anything. What the hell is Page_Load and why do I care about intercepting events to a button? Why do I need event arguments that I'm not going to use? What does this all have to do with a bank account or saving a deposit?

Absolutely nothing. You get mired in the details of the page lifecycle and all the black magic you have to employ to do what should normally be simple activities. I can never forget lessons like "Don't forget to load dynamic controls at page init or else their viewstate is lost!" or "Always load your data on prerender as events are fired after page load and you may end up displaying stale data!". I just have a hard time caring for web forms, the page request life cycle, and all the bloat that comes with their attempt at creating a stateful application on a stateless medium.

With MVC, it makes perfect sense. My workflow is clearly illustrated, my purpose is outlined with meaningfully named actions and we can get strongly typed arguments. There is no ambiguity, this is no unexpected behavior and despite it's learning curve, I can show this to anyone and they will get an idea of how the application flows.

So, this is my first impression and what I've witnessed. As a 1.0 product it's no doubt rough around the edges and it seems like there's a lot of work to be done to ease the pain of creating the views as the web controls built for web forms can't (for the most part) be dropped into an MVC view. The tutorials on the main website are also light on details. They aren't tutorials so much as they are quickstarts. I had to munge around to find out how some things worked. Other than that, it looks to be a fun platform and I'll report back when I have more dirty details about my travels in ASP.NET MVC land.

Thursday, March 26, 2009

Holy smokes, do I have a lot to learn

It's been a loooooooooong time since I really invested in my technical expertise as a developer. Sure, I've grown a ton over the last year and I've really "come into my own" but as far as the latest and greatest talks, toys and technology platforms, my head is still somewhere in late 2007. Luckily, podcasts and prolific blog writers are making my education far easier than I could have imagined. At the same time I'm absorbing massive quantities of information that I hope I can retain at least 50% of. Here's a shortlist of the craziness swimming in my mind.

I made a small quest into truly learning what Javascript is all about and I'm happy to report that it really is an awesome tool. It's been getting a bad rap for a number of years but it's really turned out to be a simple but effective language. I've been getting interested in dynamic languages overall and I used Javascript as an opportunity to check out something I've already meddled with AND I can program with nothing more than Notepad and a browser (how effing sweet is that?). Seriously, I'm sick of compilation. I waste an hour of my day every day compiling projects. But that's beside the point. Javascript is great. Go check it out, understand closure, understand that everything is a module (function, whatevs) and dynamic languages are not as scary as you've been programmed to believe.

I've begun to study domain driven design simply so I can see what all the hoopla is about. At first, you'll be patting yourself on the back since it's talking about things that any seasoned programmer is familiar with. You have your solution domain where you model your customers or orders or whatever it is that your software is trying to solve. But it's more than that. It's creating discipline and drawing lines and boundaries where you may not have considered them before. It's trying to promote clarity not purity.

Case in point, I was involved with a recent code review where I came across some code that had a distinct smell. Upon discussing the issue with the developer submitting the review it was revealed that the code existed due to a hack from an external system. Basically, the external system didn't have a way to model some financial transaction so it used another financial transaction to "hack" it into the system. For example, it's like recording a negative deposit to some banking software because the software doesn't have a function to withdraw money. Some of the DDD literature I've been reading recently points to the simple fact that we're no longer modeling the domain. We're modeling the hack of another system. Frankly, you don't need DDD to see this as a problem but it certainly brings it into perspective. It brings confusion to the codebase, to the domain, to any developers coming on board, the code that evolves from this will be as bent and unsightly as its ancestors and so forth. I may have not given this as much scrutiny had I not had so much DDD dancing through my mind.

I read Ken Schwaber and Mike Beedle's Agile Software Development with Scrum since the scrum tsunami is about to crash on my development organization. I'm drinking the Kool Aid so I'm not so concerned about whether or not it's a good methodology. The only thing that worries me is if the management cast can stomach it when I actually speak up and collaborate in ways I had never done before. If what I read is true then I should be telling them when what we're doing is ill advised. I continuously read that I am now "empowered". We'll have to see how that ultimately shakes out...

I started digging into .NET 3.5 and some of the niceties that have come to the framework. Nothing too serious but I hope to be writing a new web app with it soon. I'm particularly interested in ASP.NET MVC since that's now in 1.0. I've downloaded everything, now I just need to do something with it.

Other stuff that's on my radar but I haven't played with yet is Fluent NHibernate, Structure Map, Ruby, and DSLs. I think I may have a post or two coming to discuss some thoughts that those topics have generated for me.

In any case, my brain is running dry and it's 2am.

Wednesday, March 25, 2009

XML sucks

Friggin' namespaces. Such a pain in my ass. JUST PARSE THE GODDAM VALUE!