Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Refactor of a monster switch statement
using System;
using System.Collections.Generic;
namespace Monster
{
public class MonsterClass
{
public void DoTask()
{
MySqlConnection oSqlConn = new MySqlConnection();
List<ScheduledTask> tasksToPerform = oSqlConn.GetTasks();
try
{
foreach (ScheduledTask task in tasksToPerform)
{
TaskClassFactory.Parameters factoryParams = new TaskClassFactory.Parameters { LastRunDate = task.LastRunTime };
try
{
var taskClass = TaskClassFactory.CreateTaskClass(task.TaskName, factoryParams);
taskClass.DoWork();
task.LastRunTime = DateTime.UtcNow;
UpdateTaskRunStatus(TaskStatus.Good, task);
}
catch (Exception)
{
UpdateTaskRunStatus(TaskStatus.Error, task);
Logger.LogError("Error details here");
}
}
}
catch (Exception ex)
{
OTLogger.LogGenericError(ex);
}
finally
{
SQLConnectionHelper.CloseConnection(oSqlConn);
}
}
private void UpdateTaskRunStatus(object p, ScheduledTask task)
{
return;
}
}
public interface ITaskClass
{
void DoWork();
}
public static class TaskClassFactory
{
public static ITaskClass CreateTaskClass(string name, Parameters createParams)
{
switch (name)
{
case "Task1":
return new Task1Class(createParams.LastRunDate);
case "Task2":
return new Task2Class();
case "Task3":
return new Task3Class();
case "Task4":
return new Task4Class();
}
return null;
}
public struct Parameters
{
public DateTime LastRunDate { get; set; }
}
}
public class Task1Class : ITaskClass
{
private DateTime _lastRunDate;
public Task1Class(DateTime lastRunDate)
{
_lastRunDate = lastRunDate;
}
private void ExtractTop10Data(DateTime dtLastRun)
{
return;
}
public void DoWork()
{
ExtractTop10Data(_lastRunDate);
}
}
public class Task2Class : ITaskClass
{
private void CreateImageFeed()
{
return;
}
public void DoWork()
{
CreateImageFeed();
}
}
public class Task3Class : ITaskClass
{
private void DestroyImageFeed()
{
return;
}
public void DoWork()
{
DestroyImageFeed();
}
}
public class Task4Class : ITaskClass
{
private void ProcessData()
{
return;
}
public void DoWork()
{
ProcessData();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.