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…

Advertisements

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: