samedi 14 février 2015

Refactor static variables for Unit tests C#

I'm building an API that expose one single function. I'm trying to refactor the code for dependency injection to integrate unit tests under the composition root pattern.


The problem is that i'm using static variables witch I consider evil since it makes the code hard to refactor. The reason I used static var, is that it simplify the code when used with extensions methods.


I would like to know how to remove those static variables to integrate DI.


Here is a fictive example :


Use exemple :



using System.Collections.Generic;

namespace Extractor
{
class Program
{
static void Main(string[] args)
{
var myExtractor = new Extractor();

var dc = new DataContainer
{
Type = 1,
Data = new byte[] { 9,9,9,9,9,9,2,3}
};

myExtractor.VeryBigMethod(new List<int> { 1, 2 }, dc);
}
}
}


API :



using System;
using System.Collections.Generic;

namespace Extractor
{
public class Extractor
{
public void VeryBigMethod(List<int> config, DataContainer dc)
{
DataContainerDispatcher.Init(config);
dc.Extract();
}
}

public class DataContainer
{
public int Type { get; set; }
public byte[] Data { get; set; }
}

public static class DataContainerExt
{
public static void Extract(this DataContainer dc)
{
DataContainerDispatcher.GetExtractor(dc).Extract();
}
}


static class DataContainerDispatcher
{
private static Dictionary<int, IExtractor> _ext = new Dictionary<int, IExtractor>();

public static IExtractor GetExtractor(DataContainer dc)
{
return _ext[dc.Type];
}

public static void Init(List<int> types)
{
foreach (var t in types)
_ext.Add(t, ExtractorFactory.GetExtractor(t));
}
}

public static class ExtractorFactory
{
public static IExtractor GetExtractor(int type)
{
switch (type)
{
case 1:
return new HeaderExtractor();
case 2: return new BodyExtractor();
default:
throw new NotSupportedException();
}
}
}

public interface IExtractor
{
void Extract();
}

public class HeaderExtractor : IExtractor
{
public void Extract() { }
}

public class BodyExtractor : IExtractor
{
public void Extract() { }
}
}

Aucun commentaire:

Enregistrer un commentaire