Posts Tagged C#

Fun with C#: Dynamic Features

Most software projects I’ve worked on had at least one feature that needed to be dynamic, where certain aspects of the program wouldn’t be known until runtime. Sometimes, those aspects would be known as the application was running on the developer’s machine (data binding in WPF, for instance, is late bound), and other times, they’d only be known at the end-user’s machine (maybe based on the user’s selections, maybe based on the environment).

Before landing in the strongly-typed world of C#, I used to write software in FoxPro, which was a dynamic language. We used to store large blocks of code on tables in the database, and execute that code during run time after all the required pieces of the puzzle were known. That was not something easy to do in the early days of C#.

There are a number of ways to either add or change behavior of an application during runtime, and granted, doing things in C# exactly the same way we did in FoxPro was NOT the way to go! However, when dynamic features where introduced back in C# 4.0, I was glad to have it in my toolbox, and I believe I’ve found good use for it in several situations.

For this post, my main point is just that I think using the dynamic features in C# is fun. I’ll be writing up more posts to talk about some basic stuff around these features, and also giving some examples on how I’ve used it.

Leave a comment

Misery with C#: Regions…

I feel miserable pretty much everytime I run into regions when going through C# code. Nine out of ten times, regions are the rug where developers sweep ugly code under.

Many, many years ago, I used to use regions like many people still do:

  • to organize my class, grouping fields, properties, methods, etc;
  • to group code according to its functionality (methods and properties related to save go here, those related to validate go there, etc.)

Eventually I finally learned that even that way of using regions was pretty bad. If a class is so big that in order to make it easier to read I need to group and hide things under regions, that means the class is doing too much. Also, if there are multiple groups of funcionality within the same class, that probably means each of those groups represent abstractions that belong somewhere else.

Now, what’s even more aggravating is using regions within method bodies. So you have code, code, code, region, code, code, region, code. I’ve seen methods that had switch-blocks where each case block had code hidden behind regions!!. If some code is within a region inside of a method body, than that code should probably be moved to a separate method!

Now, what do we make out of the example below?

The entire body of that method is hidden behind a region. What should expect to find when we expand that region? Just a few lines of the cleanest code possible, right…? Yeah, right!

If you’re using regions like that, please, take a step back and think how you can get rid of that nasty rug. 🙂

Leave a comment

Fun with C#: Cleaning up dense code with Dictionary and ForEach

I have a personal dislike for code produced by copy-and-paste that forces me to read it over several times so I can spot what’s changed after the block was pasted. Take the code below as an example:

After a while we spot the differences:

There cases where spotting the difference isn’t so easy. Sometimes, it’s a simple “!” somewhere in the code that can be easily overlooked.

Anyway, a couple of posts ago I mentioned how I use dictionary and delegates to get rid of switch-blocks, as well as how I like using ForEach whenever possible. Well, we can clean things up a bit in the code above using the same approach, changing the code to make it look like this:

Much better, I think…

Leave a comment

Fun with C#: Object and Collection initializers

I hate looking at dense code. You know, that kind of code that has blocks that look like bricks left randomly around the room, making it very easy for anyone to walk around the place.

Serioulsy, dense code is hard to read and understand. Let’s take this little bit of code as an example:

 

When I run into code that looks like that, this is sort of what I see:

It’s so easy to put that garbage out, like this:

The same happens with collections…

I like this much better:

I always favor using object/collection initializers whenever possible, if that makes the code more compact and easier, more calm to read.

1 Comment

Fun with C#: Create fluent assertions for your domain

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.

2 Comments

Fun with C#: Create a handy calendar using Iterators

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.

Leave a comment

Fun with C#: Using delegates to get rid of switch-blocks

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

Leave a comment