The class that will be refactored is the ParameterCheck
class. This class defines parameters using reflection.
Listing 1
using System;
using System.Reflection;
namespace Nucleo.Reflection
{
public class ParameterCheck
{
private object _argument = null;
private ParameterCheckType _type;
private enum ParameterCheckType
{
Any, Type, NotNull, Null
}
private ParameterCheck(ParameterCheckType type)
{
_type = type;
}
private ParameterCheck(ParameterCheckType type, object argument): this(type)
{
_argument = argument;
}
public static ParameterCheck Any()
{
return new ParameterCheck(ParameterCheckType.Any);
}
public static ParameterCheck IsOfType(Type type)
{
return new ParameterCheck(ParameterCheckType.Type, type);
}
public static ParameterCheck IsNotNull()
{
return new ParameterCheck(ParameterCheckType.NotNull);
}
public static ParameterCheck IsNull()
{
return new ParameterCheck(ParameterCheckType.Null);
}
internal static bool ProcessIsOfType(object source, Type type)
{
if (source != null)
return source.GetType().IsAssignableFrom(type);
else
return false;
}
internal static bool ProcessIsNotNull(object source)
{
return (source != null);
}
internal static bool ProcessIsNull(object source)
{
return (source == null);
}
internal static bool ProcessObject(object source, ParameterCheck check)
{
if (check._type == ParameterCheckType.Any)
return true;
else if (check._type == ParameterCheckType.NotNull)
return ProcessIsNotNull(source);
else if (check._type == ParameterCheckType.Null)
return ProcessIsNull(source);
else if (check._type == ParameterCheckType.Type)
return ProcessIsOfType(source, (Type)check._argument);
else
return true;
}
}
}
Now, this class is not exactly terrible in size at the
moment. However, as we add more parameter checks, it will quickly grow in
size. Because of this, a better way to represent this object is to use the
state/strategy pattern.