Design patterns and TDD

Every computer science student heard about design patterns. A design pattern is a general solution to a problem that repeatedly occurs in software implementation. Correct use of patterns, where appropriate, lead to code that can be easily reused for different situations.

Patterns are very useful. There are situations in which applying a pattern will not only allow you to reuse  your code, but also to solve your problem more elegantly. As a downside, there are many situations in which applying a pattern may be like shooting mice with a bazooka. Think about a small component of your system which is not gonna be reused anywhere else.

One of the mantras of XP - and of course one of the foundations of TDD - is to keep your implementation as simple as possible. The YAGNI principle (You Aren't Gonna Need It) forces us to be focused on what's really needed by our solution, and to not bloat the code with unnecessary logic. To some extent, this may be seen as discouraging the use of patterns. After all, sometimes when implementing a pattern we are implementing some logic that we don't need or we foresee we need (but we're not sure after all).

Is this real? Does TDD clash with the concept of design patterns?

When thinking about patterns, we should keep in mind that in the Gang of Four design patterns are seen as a target to which our refactoring should aim. Hence, design patterns are naturally linked with refactoring, which of course is one of the foundations of TDD (you don't skip the refactor phase while doing TDD, do you...). When you refactor your code, common behaviour and smells need to be identified and moved towards a cleaner and better implementation - which may very well be a pattern.

A very interesting book I'm reading at the moment is Refactoring to Patterns by Joshua Kerievsky - it's a practical and pragmatic approach on how to identify common situations while refactoring your code, and how to move to, towards or away from design patterns. I haven't finished it yet, but from what I've read I bet it's gonna be on my desk whenever I write some code.

And you, have you ever refactored to patterns?