Wednesday, December 21, 2016

Tuple Dictionary Key ???

The other day myself and some coworkers where going over some ideas on refactoring a process.  In this conversation the idea of a dictionary key of a tuple came up.  I thought this has to work especially after my last post about dictionaries => Fun with Dictionaries – Replacing ugly switch and if statements

So below is some code showing my findings.  Also here is the link to my github with all the code (https://github.com/devdaves/FunWithDictionaries2)

Here is an example factory where the dictionary with a tuple key is instantiated and used.

Using the Tuple as a key you can actually take some extremely complicated logic with multiple options and turn it into a simple dictionary lookup.

Tuesday, November 1, 2016

Building objects for your Unit Tests

When creating unit tests I prefer to use the AAA pattern (Arrange, Act and Assert).  During the Arrange part you usually end up instantiating objects to use for the test.  Depending on the complexity of the objects you are creating this can get to be a little bit of code.  Lets look at the code below:

Note the method BuildContact.  It takes a parameter of an Action<Contact> which would allow you to pass in a lambda expression to further define the properties you want to change on the Contact object for each unit test individually.  This centralizes the logic needed to create the Contact which is helpful but another benefit is what if there was a default value used by every test.  Look at this version of the BuildContact method:

Note the defaults are before the invoking of the action.  This way if a test wanted to override the default values it can.  Normally I create a separate test class for each of the methods I am writing unit tests for.  Using this method above to create the item I am using allows me to create the object with many defaults already set.It wouldn’t be unusual to have several BuildContact methods in different test classes each specific to the needs of that class (method) specifically.

Friday, October 28, 2016

Fun with Dictionaries – Replacing ugly switch and if statements

Recently I have been using a new technique to replace those ugly if statements and switch statements with a dictionary.  Lets get started with some code first:

So that Build method with all the if statements isn’t very appealing.  Lets make it better by using a switch statement instead:

That is better but I have started to prefer using a dictionary instead.  I think this code looks better:

Adding new items is one line now instead of several with the if and switch statements.