Refactoring to State/Strategy
page 2 of 4
by Brian Mains
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 21297/ 65

Parameter Checking Example

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.


View Entire Article

User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2021 ASPAlliance.com  |  Page Processed at 2021-11-29 10:26:02 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search