Sep 15
Getting started with TDD
icon1 Darrell Mozingo | icon2 Musings, Testing | icon4 September 15th, 2011| icon3No Comments »

When I first read about TDD and saw all the super simple examples that litter the inter-tubes, like the calculator that does nothing but add and subtract, I thought the whole thing was pretty stupid and its approach to development was too naive. Thankfully I didn’t write the practice off – I started trying it, plugging away here and there. One thing I eventually figured out was that TDD is a lot like math. You start out easy (addition/subtraction), and continue building on those fundamentals as you get used to it.

So my suggestion to those starting down the TDD path is: don’t brush it off. Start simple. Do the simple calculator, the stack, or the bowling game. Don’t start thinking about how to mix in databases, UI’s, web servers, and all that other crud with the tests. Yes, these examples are easy, and yes they ignore a lot of stuff you need to use in your daily job, but that’s sort of the point. They’ll seem weird and contrived at first, but that’s OK. It serves a very real purpose. TDD has been around for a good while now, it’s not some fad that’s going away. People use it and get real value out of it.

The basic practice examples getting you used to the TDD flow – red, green, refactor. That’s the whole point of things like kata’s. Convert that flow into muscle memory. Get it ingrained in your brain, so when you start learning the more advanced practices (DIP, IoC containers, mocking, etc), you’ll just be building on that same basic flow. Write a failing test, make it pass, clean up. You don’t want to abandon that once you start learning more and going faster.

It seems everyone gets the red-green-refactor part down when they’re doing the simple examples, but forget it once they start working on production code. Sure, you don’t always know what your code is going to do or look like, but that’s why we have the tests. If you can’t even begin to imagine how your tests will work, write some throw away spike code. Get it working functionally, then delete it all and start again using TDD. You’ll be surprised how it changes.

Good luck with your journey. If you’re in the Canton area, don’t forget to check out the monthly Canton Software Craftsmanship meetup. There are experienced people there that are eager to help you out.

Jul 28
Commenting out old code kills puppies
icon1 Darrell Mozingo | icon2 Musings | icon4 July 28th, 2011| icon31 Comment »

There, I said it. Actually, I’m kind of worried that title won’t adequately state the intensity of this situation.

This is one of the fundamental reasons we have source control people, so we can go back through a file’s history and see the different revisions. Please, for the love of all that is holy, don’t comment out old code. Just delete it! Feel free to slap your own knuckles with a ruler if you start to think about commenting it. Don’t try to recreate a source control system through commented out code. Everyone knows exactly what I’m talking about:

// John Doe - 7/5/2011 - Changed to allow a higher limit.
// dozens of lines of old code....
// John Doe - 7/18/2011 - Changed algorithm slightly.
// dozens of lines of old code....
// random dozen lines of old code with no comment at all
public void ActualCode() { }

Those extra comment chunks are just crap to sift through to get to the real code, extra stuff you’ll have to parse to see if it’s relevant to the current situation, and creating more false-positives for ReSharper (and I’m guessing other refactoring tools) to pick up when you rename a variable/method that’s used inside those commented chunks. That chunk of old code at the bottom without even a hint as to why it’s commented out? That’s the worst of the worst – someone’s going to sit there and stare at it for a good while before they figure out why it was commented out, and we know when the author actually committed this file with that commented out the commit comment was blank too. Awesome.

So anyway, just remember what actually happens the next time you’re about to comment out old code and don’t do it, you’ll be doing future programers (and more than likely yourself) a huge service…

Commenting code kills puppies

Apr 11
Know your tools
icon1 Darrell Mozingo | icon2 Musings | icon4 April 11th, 2011| icon34 Comments »


How many carpenters do you think don’t know about kerf widths? How many plumbers don’t know the difference between MAPP and propane for soldering? Probably not many.

Masters of their craft know their tools inside and out. They don’t just skirt by barely knowing how to use them, and end up taking longer to complete a job because of that. We have the same situation in our craft. We use tools day in and day out – our IDE’s, debugging tools (for our main languages and web based ones), OS, browsers, websites, etc. They’re all tools of our trade. Learning how to really use them is just another stepping stone on the path to being a craftsman.

The best way to really make use of your tools and increase your programming speed is to ditch the mouse. Use the keyboard as much as possible, which can be almost everything. Really get good with the keyboard and you’ll be amazed at how much more efficiently you can pump out code and navigate around.

I use Windows and Visual Studio, so I’ll use that as an example. Visual Studio itself has a metric ton of built-in keyboard shortcuts, but add ReSharper to the mix, and you’re golden. Check out the keyboard shortcut cheat sheet, it’s ridiculous, and overwhelming. Pick one or two shortcuts you think you’ll use, then use those exclusively for a week. Make sure to purposely use them as much as possible until they become muscle memory. It won’t take long.

Look at Tools -> Settings -> Keyboard. There’s lots of stuff you can key bind on your own that doesn’t come setup by default. Create a key combination to run your unit tests rather than reaching for the mouse. If a default key combo feels unnatural for you, rebind it. Find something that works for you, and don’t be afraid to experiment.

Start learning keyboard shortcuts in other programs you use on a regular basis. There’s cheat sheets for GMail and Google Reader. For your mouse-free text editing needs (and IDE needs if you’re super experimentative and working with .NET) there’s the grand-daddies themselves: VIM and Emacs. There’s even plugins for Firefox (Vimperator) and Chrome (Vimium) to make each browser navigable in a VIM-esque way, and other plugins for each browser to simply add more keyboard navigation tricks. Heck, there’s even a few VIM plugins for Visual Studio itself if you want to go all the way, including ViEmu (paid) and VsVim (free).

It’s also super helpful to get a keystroke launcher on your box, such as Executor (my personal favorite) or Launchy. These guys basically give you the standard Windows Run dialog on steroids – letting you make custom launch commands and scripts. Definitely play around with one of these and work it into your normal workflow. I find myself leaning on it all the time.

So start practicing with a keyboard-only setup today. Disable your mouse driver and force yourself. It’ll kill your productivity in the short term for sure, but it’ll pay dividends every day for the rest of your career once you get used to it. You’ll thank me in a few weeks. Seriously, I’m marking my calendar.

Sep 2
Comments are just missed refactorings
icon1 Darrell Mozingo | icon2 Musings | icon4 September 2nd, 2010| icon32 Comments »

Ah comments, those delectable little nuggets of static information that routinely get out of sync with your code’s intention. Actually, I’m sort of excited when I run into them though. See, to me they represent missed refactorings that are usually pretty easy to implement.

Say you run across a piece of code like this:

public void ProcessOrder(Order order)
	// If the order is on hold, figure out why and get the next availability date.
	if (order.Status == OrderStatus.OnHold && order.OrderDate < DateTime.Now)
		// <imagine complex logic to check reason here...>
		order.OnHoldReason = (result of complex logic above);
		// <imagine complex logic to get the next available date here...>
		order.NextAvailableDate = (result of complex logic above);

So it’s usually not this obvious in real code bases, but almost every time I’ve run into a grouping of comments in this arrangement it could be boiled down into something this simple. Can you see the refactoring potential? It’s pretty easy – extracting some variables and methods based upon the text in the comment:

public void ProcessOrder(Order order)
	var orderIsOnHold = (order.Status == OrderStatus.OnHold && order.OrderDate < DateTime.Now);
	if (orderIsOnHold)
		order.OnHoldReason = getOnHoldReason(order)
		order.NextAvailableDate = getNextAvailableDate(order);
public string getOnHoldReason(Order order)
	return // <imagine complex logic to check reason here...>
public DateTime getNextAvailableDate(Order order)
	return // <imagine complex logic to get the next available date here...>

Like I said, it’s not much and it’s certainly not hard (a few keystrokes in Visual Studio, with or without ReSharper), but it moves the comments from sitting idly above the code, not participating, to being true first class citizens in the program in the form of variable and method names. It doesn’t guarantee they’ll be updated with the code if the logic changes in the future, but it gives them a lot better shot at it. I mean, there aren’t really developers out there lazy enough to update the intention of a variable or method and not change the name, right? Right?

Aug 19
Clever vs Explicit
icon1 Darrell Mozingo | icon2 Musings | icon4 August 19th, 2010| icon31 Comment »

When we all start out developing, either through classes in high school/college or slowly on our own time, we inevitably want to write code thats super clever. Like, use-3-lines-to-express-what-used-to-take-20-lines type of clever. We see less code and we’re pleased. All is good and well with the world.

Until you look at that code a few months down the road and wounder what the hell you were smoking, and it takes you almost as long to decipher it again as it did to write it in the first place. All of a sudden saving those few extra lines of code don’t seem so smart, huh?

The simple fact of the matter is you spend more time maintaining code than you do writing it in the first place, so being more explicit in your code always trumps being clever to save a few lines. Always.

There’s the obvious places where people get clever, like algorithms or loops, but there’s plenty of other places too. Places where I wouldn’t really call it “being clever”, or at least I’m sure the original authors never thought they were trying to be clever when they wrote it. It was probably just quicker to write it in a certain way. For example, take this code:

var mappedEmployees = new List<EmployeeViewModel>();
foreach (var employee in _employeeRepository.All().Where(x => x.IsRetired == false && x.Salary > 100000))
return View(mappedEmployees);

It’s not really hard to read, but it’s not really easy either. It might take you an extra second or two to figure out what’s going on when you first look at (even if you wrote it a few months ago), but multiply that by how many places you see code like this and how often you go back in to modify it (for new features, bugs, whatever). It adds up, quick. Written more explicitly, it might look something like this:

var mappedEmployees = new List<EmployeeViewModel>();
var nonRetiredHighEarningEmployees = _employeeRepository.All().Where(x => x.IsRetired == false && x.Salary > 100000);
foreach (var nonRetiredHighEarningEmployee in nonRetiredHighEarningEmployees)
	var mappedEmployee = _employeeMapper.Map(nonRetiredHighEarningEmployee);
return View(mappedEmployees);

You might call it verbose, but I’d say it’s a net gain. Each line is doing one thing. Yon can step through and read it without mentally pulling pieces apart. None of this “OK, that’s the mapped object call there, and its return is going into the collection there, and the whole thing is looping through that query there”. Things are given names and methods aren’t nested inside each other.

Always be on the lookout for “clever” areas in your code. Be explicit. Try to stick to each line doing one thing so there’s no hidden surprises.

Feb 7
icon1 Darrell Mozingo | icon2 Musings | icon4 February 7th, 2010| icon3No Comments »

Alright people, we’re not on 8088’s with 20M hard drives anymore. It’s OK, and in fact recommended, to stretch out your variable and method names so they make sense. We don’t need variables with names like x, col, or cAcctNum anymore. Use Intellisense and don’t be afraid to type a bit when you first enter the names. Meaningful names like employeeCount are good, as is getting rid of stupid one-off abbreviations and instead opting for naming like column and clientAccountNumber.

By using a shortened variable or method name, you’re forcing some other developer in the future (who often ends up being yourself) to mentally substitute that shortened version in their head each time they see it while reading through your code. Lets face it, our code is usually hard enough to understand long after we’ve written it just on its own, so strive to do everything possible to more quickly and easily figure it out in the future. Those small substation times accumulate pretty quick when you’re trying to find a bug in foreign code.

Queue the contrived example:

public int AddEmp(string fname, string lname, decimal rate, Dept dept)
	var emp = EmpFact.CreateEmp(fname, lname, rate, dept);
	var x = 0;
	foreach(var emp in this.Employees)
	return x;

Yea yea, like I said, contrived. Anyway, while you can probably tell somewhat easily what’s going on there, you can see there’s a lot of common and not so common abbreviations and shortened names being used. Dept? x? What they hell do they do? Lets try this again without being quite so lazy:

public int AddEmployee(string firstName, string lastName, decimal payRate, Department department)
	var newEmployee = EmployeeFactory.CreateEmployee(firstName, lastName, payRate, department);
	var newEmployeeCount = 0;
	foreach(var employee in this.Employees)
	return newEmployeeCount;

A bit better, I’d say. On your first read through this code it’s easier to see what’s going on and what each piece plays in the puzzle. You don’t have to stop for a split second to think “first name” when you see “fname”. You just read “first name”.

I know a lot of people scoff at longer names when they first see them (like FindAllCustomersInStateNotUsingDiscountWhenAvailable), but that’s cool. It is weird at first, but you get used to it. Even more foreign to most developers is using underlines for spacing: Find_all_customers_in_state_not_using_discount_when_available. I personally find that version even more readable as you don’t have to mentally parse the words, but it’s a hard pill for a lot of developers to swallow.

Regardless of how you do it, the next time you find yourself using a quick abbreviation or some meaningless variable/method name, please do your future self and other developers a favor by putting some meaning into it.

Jul 17
Crisis as Opportunity
icon1 Darrell Mozingo | icon2 Musings | icon4 July 17th, 2009| icon31 Comment »

I’m currently reading through Eric Evan’s Domain Driven Design. It’s quite a good read – a bit thick at times, but still very much grounded in pragmatism and real life. One smaller section really stood out at me recently, titled “Crisis as Opportunity”, and begins on page 325. Here’s a few of the more meaningful portions from that section:

“A period of steady refinement of a model can suddenly bring you to an insight that shakes up everything…Such a situation often does not look like an opportunity; it seems more like a crisis. Suddenly there is some obvious inadequacy in the model…Maybe it makes statements that are just wrong. This means the team has reached a new level of understanding. From their now-elevated viewpoint, the old model looks poor. From that viewpoint, they can conceive a far better one.”

Its something that’s happened to my team a few times on our current project so far – seeming like we hit a brick wall on an issue. Certain parts of the code base were having to be bended and twisted all sorts of ways to meet new requirements, producing far uglier code than when we first wrote it. These areas seemed to dragging us down, but the constant onslaught of requirements pretty much forced us to push through and find a better way.

Taking a step back from the situation provided a great view that allowed us to use some new understanding of the domain, our current code base, and where we knew it was heading in the not too distant future, to refactor for “deeper insight”, as Evans calls it. Introducing elements that were implicitly in the design as explicit objects and methods was exactly what we needed. The former problems areas were then much easier to work with, allowing new requirements to be added at a much faster pace.

I now almost look forward to hitting a brick wall when trying to add new requirements to our domain. It means our domain needs work and we could be on the cusp of a nice big ‘ol refactoring to gain more insight, and I love my insight.

Apr 8
Freedom or mentoring?
icon1 Darrell Mozingo | icon2 Musings | icon4 April 8th, 2009| icon36 Comments »

Let’s take a hypothetical here and say you’re looking at two jobs. They’re at roughly similar companies which we’ll call Company A and Company B (I know, I know, original, right?). You’d be working on similar projects at either and they both have comparable co-workers. For all intents and purposes they’re equal, save for one glaring difference:

  • Company A gives you more freedom to “explore”. You’re more or less given time to read up on things, try new technologies & methodologies knowing full well some will fail and basically waste time (and given some extra slack in your schedule to compensate), get some extra training here and there, and not have a pink slip waived in front of you if you happen to let a few bugs through to production.
  • Company B has one or more senior developers that honestly love their craft, push continous learning, and can mentor you in advanced – and “proper” – directions and techniques. Test driven development? Check. SOLID principals and their real-world application? Check. Domain driven design? Check. I’m not just talking about guys that have read up on these topics either, but that have years of experience in them and a metric crap load of failures under their belts that they’re willing to share inorder to help insure you don’t fall into them too. They take pride in all aspects of their job and won’t stand for letting things slide.

Which would you choose?

It’s tough. The benefits Company A provides could get you to the same end goal as Company B, albeit at a slower pace. Company B would presumably be stricter on slip-ups and time management, so if you’re using a technology you’re not terribly interested in or you’re taking a route you don’t agree with, there’s not much you can do without working on your dime.

You’re not guaranteed to ever reach that same end goal with Company A as you would with Company B, though. Self learning is a difficult, slippery slope. You have to encounter all those failures yourself and actually overcome them. Granted, failing for yourself teaches you something more than just hearing a warning from a mentor, but those failures take time, and I believe there’s a quote about these situations… something along the lines of “Those who fail to learn from history, are doomed to repeat it”, I believe.

Me, personally? I’m not sure. I can see it both ways, though I’ve only had the pleasure (?) of working with companys similar Company A. It’s a tough decision, and my answer probably depends on what day you ask me. I know I’d like to see what the other side of the fence has to offer though.

What’s your take?