Monday, August 05, 2013

Why I finally began to like TDD

I actually wrote this Controller Method in Ruby, but I will translate it to C# style. This is why I finally began to like TDD. Notice that there is a single call to Model (Movie) from Controller Method.

Without TDD

String ByDirector(int id)
{
 Movie movie = Movie.Find(id);
 if (movie.director == null || movie.director.size == 0)
 {
  String text = movie.title + " has no director info";
  this.Flash(FlashType.Warning, text);
  return RedirectToAction("HomePage");
 }
 this.movies = Movie.where("director = " + movie.director);
}

With TDD

String ByDirector(int id)
{
 try
 {
  this.movies = Movie.FindByDirector(id);
 }
 catch (NoDirectorException e)
 {
  this.Flash(FlashType.Warning, e.description);
  return RedirectToAction("HomePage");
 }
}