Wednesday, December 2, 2015

Tiny Improvements - C# - Useless checks

Going to start putting in tiny ways to improve code when I find minorly irritating code:

if (myDictionary.ContainsKey(myKey)) {
    myDictionary.Remove(myKey);
}

When I see this code I wonder what happens when I call remove something that isn't there. Does it throw an exception? Checked the API, just changes what is returned by the remove call. This code can be shortened to:

myDictionary.Remove(myKey);

This reduces your cyclomatic complexity by one.

If the case that Remove threw an exception on removing something not there the logical thing to do would be to create an extension method on dictionary that could be called something like 'SafeRemove'. This would also reduce your project wide cyclomatic complexity by the number of times you used this pattern minus one.

No comments:

Post a Comment