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…

2 responses to “Fun with C#: Cleaning up dense code with Dictionary and ForEach”

  1. […] Fun with C#: Cleaning up dense code with Dictionary and ForEach […]

  2. […] Instead of repeating code, define what needs to be done, and then determine how to process them in one place. The result is cleaner, easier to read, and much easier to change later. See an example here. […]

Leave a Reply

Trending

Discover more from Claudio Lassala's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading