Archive for February, 2017
Fun with C#: Create fluent assertions for your domain
Posted by claudiolassala in fun with C# on February 22, 2017
When writing tests, we should strive to make the test code just as good (if not better) as the production code. Embedding your domain’s language into your test assertions can help a lot with that.
Take the following example:
[TestMethod] public void MeatLover() { var pizzaMaker = new PizzaMaker(); var meatLoverPizza = pizzaMaker.MakeMeatLover(); Assert.IsTrue(meatLoverPizza.Toppings.Any(topping => topping.Name == "Pepperoni")); Assert.IsTrue(meatLoverPizza.Toppings.Any(topping => topping.Name == "Italian sausage")); Assert.IsTrue(meatLoverPizza.Toppings.Any(topping => topping.Name == "bacon")); Assert.IsTrue(meatLoverPizza.Toppings.Any(topping => topping.Name == "ham")); Assert.IsTrue(meatLoverPizza.Toppings.Any(topping => topping.Name == "mozzarella")); }
Our PizzaMaker class is supposed to make meat lover pizzas, so whenever it does, it’s expected to have a specific list of toppings on it. The test above captures that requirement. However, the assertions are very noisy. I’d like to have my test read like so instead:
[TestMethod] public void MeatLover() { var pizzaMaker = new PizzaMaker(); var meatLoverPizza = pizzaMaker.MakeMeatLover(); meatLoverPizza.ShouldHaveToppings("Pepperoni", "Italian sausage", "bacon", "ham", "mozzarella"); }
Notice that code in the test no longer has things like calls to Assert, or Any, or lambdas. It only has the bare minimum required by the C# compiler, and it is a lot easier to read so we understand the actual requirement being verified. Writing the tests that way allows me to collaborate with other developers, QA, and Business Analysts, as they can follow the code a lot more easily.
So, where does the ShouldHaveToppings method for the Pizza class comes from? A simple Extension Method:
public static class PizzaAssertionExtensions { public static void ShouldHaveToppings(this Pizza pizza, params string[] toppingNames) { foreach (var toppingName in toppingNames) { Assert.IsTrue(pizza.Toppings.Any(topping => topping.Name == toppingName), "Topping missing: " + toppingName); } } }
To make things even better, I’d like my code to read like this:
meatLoverPizza.Should().HaveToppings("Pepperoni", "Italian sausage", "bacon", "ham", "mozzarella");
That way, my extension method would simply be called HaveToppings. In order to implement it that way, I’d look into making my fluent assertions extend FluentAssertions.
In summary, instead of just using plain calls to Assert, create fluent assertions that map to the nouns and verbs that exist in your domain.
Fun with C#: Create a handy calendar using Iterators
Posted by claudiolassala in fun with C#, Software Development on February 16, 2017
Here’s something fun with can do with C#. Imagine we need to work with dates within a given year. For instance, I want to list out all days within the year of 2017. A little Calendar class like the one below would be handy:
var calendar = new Calendar(2017); var days = calendar; foreach (var day in days) { Console.WriteLine(day); }
The output looks somewhat like this:
What if I wanted to list all days in january, like so:
var days = calendar. Where(d => d.Month == 1);
The output:
Last but not least, maybe I want to list all Saturdays in january:
var days = calendar.Where(d => d.Month == 1 && d.DayOfWeek == DayOfWeek.Saturday))
The output:
One could think that under the hood the Calendar class uses some sort of Collection, Array or List of DateTime objects. In reality, it uses an iterator, implemented using the yield return keywords:
public class Calendar : IEnumerable<DateTime>
{
readonly int _year;public Calendar(int year)
{
_year = year;
}public IEnumerator<DateTime> GetEnumerator()
{
var firstDayOfTheYear = new DateTime(_year, 1, 1);
var lastDayOfTheYear = new DateTime(_year, 12, 31);
var daysInTheYear = (lastDayOfTheYear - firstDayOfTheYear).TotalDays;for (int i = 0; i <= daysInTheYear; i++)
{
yield return firstDayOfTheYear.AddDays(i);
}
}IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Ain’t that fun and handy? 🙂
I really like this combination of IEnumerable<T>, iterators, and LINQ.
Speaking at the North Houston .NET User Group this week
Posted by claudiolassala in Presentations on February 13, 2017
I’m speaking at the North Houston .NET User Group this week, on Feb 16 at 6:30pm. This is a new session I’ve put together. Check this out:
Code Review: I mean no harm
As part of the work I’ve been doing for many years, I get to do a lot of code review. I usually document things that come up doing a code review so I can share it with other developers in the teams. In this session, I share some of the code I’ve looked at, the reasons why the code raised yellow or red flags in my head, and possible solutions I’ve proposed.
Speaking at the Houston .NET User Group this week
Posted by claudiolassala in Presentations on February 8, 2017
I’m speaking at the Houston .NET User Group this Thursday, February 9, at 6:30pm. Click here to find out about location and other details.
I’ll be delivering a brand new session. Check out the title:
The Software Does Not Work? Rewrite it!
What’s this session really about?
Outdated technology? Unmaintainable codebase? Politics? Those are just some of the reasons that cause software rewrites. Whether a rewrite is really what is needed or not, chances are we all work in such projects.
Do we rewrite the entire software? Can we rewrite just parts of it? Where do we start? Can we automate the process?
In the last 15 years, I’ve worked in a variety of such projects. I’d like to share the most important lessons I’ve learned in these projects. In this talk, I’ll share the different types of rewrites and techniques, what I learned from it, and how it changed my way of approaching both software rewrites as well as greenfield projects.
I want your feedback!!
I hope to see some of my readers there! If you do show up there, please rate my session afterwards and provide me some feedback here! Like I said, it’s a brand new session, so I’m looking forward to constructive criticism so I can improve my material.
Fun with C#: Using delegates to get rid of switch-blocks
Posted by claudiolassala in fun with C#, Software Development on February 7, 2017
I’m starting a new series here: Fun with C#! The idea is to post a couple of things I do in this cool language. 🙂
When I talk about Clean Code with developers, an example that I always use is switch-blocks. Every bad code out there always features abusive use of switch-blocks. In most cases, those blocks start off very simple, with one-liners, like the sample below:
public void DoStuff(DayOfTheWeek dayOfTheWeek) { switch (dayOfTheWeek) { case DayOfTheWeek.Sunday: Console.WriteLine("Do stuff for Sunday..."); break; case DayOfTheWeek.Monday: Console.WriteLine("Do stuff for Monday..."); break; case DayOfTheWeek.Tuesday: Console.WriteLine("Do stuff for Tuesday..."); break; case DayOfTheWeek.Wednesday: Console.WriteLine("Do stuff for Wednesday..."); break; case DayOfTheWeek.Thursday: Console.WriteLine("Do stuff for Thursday..."); break; case DayOfTheWeek.Friday: Console.WriteLine("Do stuff for Friday..."); break; case DayOfTheWeek.Saturday: Console.WriteLine("Do stuff for Saturday..."); break; } }
It always start off simple like that. Next thing you know, there’s another “simple change” that comes in, and now the code looks somewhat like this:
public void DoStuff(DayOfTheWeek dayOfTheWeek, TimeOfTheDay timeOfTheDay) { switch (dayOfTheWeek) { case DayOfTheWeek.Sunday: Console.WriteLine("Do stuff for Sunday..."); if (timeOfTheDay == TimeOfTheDay.Evening) { Console.WriteLine("Go to bed early!"); } break; ... case DayOfTheWeek.Saturday: if (timeOfTheDay == TimeOfTheDay.Morning) { Console.WriteLine("You may stay a little longer in bed..."); } else { Console.WriteLine("Do stuff for Saturday..."); } break; } }
Then comes an if-else, a for-loop, a switch-block (yes, inside the other switch, of course), and that one method becomes a terrible mess.
Well, whenever I see a case like that, I consider changing the switch-block into a dictionary of actions. I populate a dictionary with the individual blocks of code I need executed, and then I get the delegate out of the dictionary and invoke it whenever needed. The updated code would look like this:
readonly Dictionary<DayOfTheWeek, Action<TimeOfTheDay>> _dailyActions =
new Dictionary<DayOfTheWeek, Action<TimeOfTheDay>>();public FamousSwitch()
{
_dailyActions.Add(DayOfTheWeek.Sunday, DoSunday());
_dailyActions.Add(DayOfTheWeek.Monday, DoMonday());
_dailyActions.Add(DayOfTheWeek.Tuesday, DoTuesday());
_dailyActions.Add(DayOfTheWeek.Wednesday, DoWednesday());
_dailyActions.Add(DayOfTheWeek.Thursday, DoThursday());
_dailyActions.Add(DayOfTheWeek.Friday, DoFriday());
_dailyActions.Add(DayOfTheWeek.Saturday, DoSaturday());
}Action<TimeOfTheDay> DoSaturday()
{
return timeOfTheDay =>
{
if (timeOfTheDay == TimeOfTheDay.Morning)
{
Console.WriteLine("You may stay a little longer in bed...");
}
else
{
Console.WriteLine("Do stuff for Saturday...");
}
};
}Action<TimeOfTheDay> DoFriday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Friday...");
}Action<TimeOfTheDay> DoThursday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Thursday...");
}Action<TimeOfTheDay> DoWednesday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Wednesday...");
}Action<TimeOfTheDay> DoTuesday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Tuesday...");
}Action<TimeOfTheDay> DoMonday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Monday...");
}Action<TimeOfTheDay> DoSunday()
{
return timeOfTheDay =>
{
Console.WriteLine("Do stuff for Sunday...");
if (timeOfTheDay == TimeOfTheDay.Evening)
{
Console.WriteLine("Go to bed early!");
}
};
}public void DoStuff(DayOfTheWeek dayOfTheWeek)
{
_dailyActions[dayOfTheWeek].Invoke(TimeOfTheDay.Morning);
}
I like keeping the smaller individual methods for each operation. Most often than not, I’ll end up moving those separate methods into one separate class, and very often, will turn that one separate class into several separate classes.
Anyway…
- I like using a dictionary of delegates instead of using switch-blocks;
- I like having small methods a lot better than having one long method