Created
April 16, 2012 09:57
-
-
Save markrendle/2397400 to your computer and use it in GitHub Desktop.
Response to http://www.paulstack.co.uk/blog/post/my-approach-to-refactoring-a-monster-switch-statement.aspx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TaskExecutor | |
{ | |
private ITaskProcessor _processor; | |
public TaskExecutor(ITaskProcessor processor) | |
{ | |
_processor = processor; | |
} | |
public void DoTask() | |
{ | |
SqlConnection oSqlConn = new SqlConnection(); | |
List<ScheduledTask> tasksToPerform = oSqlConn.GetTasks(); | |
try | |
{ | |
foreach (ScheduledTask task in tasksToPerform) | |
{ | |
_processor.ProcessTask(task); | |
} | |
} | |
catch (Exception ex) | |
{ | |
OTLogger.LogGenericError(ex); | |
} | |
finally | |
{ | |
SQLConnectionHelper.CloseConnection(oSqlConn); | |
} | |
} | |
} | |
public interface ITaskProcessor | |
{ | |
void ProcessTask(ScheduledTask task); | |
} | |
public class TaskProcessor | |
{ | |
private readonly Dictionary<string, Runner> _runners | |
{ | |
get | |
{ | |
return new Dictionary<string, Runner> | |
{ | |
{"Task1", RunTask1}, | |
{"Task2", RunTask2}, | |
{"Task3", RunTask3}, | |
{"Task4", RunTask4} | |
}; | |
} | |
} | |
public void ProcessTask(ScheduledTask task) | |
{ | |
Runner runner; | |
if (_runners.TryGetValue(task.Name, out runner)) | |
{ | |
runner.Run(task); | |
} | |
} | |
} | |
public abstract class Runner | |
{ | |
public void Run(ScheduledTask task) | |
{ | |
try | |
{ | |
DoTask(task); | |
task.LastRunTime = DateTime.UtcNow; | |
UpdateTaskRunStatus(TaskStatus.Good, task); | |
} | |
catch (Exception ex) | |
{ | |
UpdateTaskRunStatus(TaskStatus.Error, task); | |
Logger.LogError("Error details here"); | |
} | |
} | |
protected abstract void DoTask(ScheduledTask task); | |
} | |
public class Task1Runner : Runner | |
{ | |
protected override void DoTask(ScheduledTask task) | |
{ | |
var task1Class = new Task1Class(); | |
task1Class.ExtractTop10Data(task.LastRunTime); | |
} | |
} | |
public class Task2Runner : Runner | |
{ | |
protected override void DoTask(ScheduledTask task) | |
{ | |
var task2Class = new Task2Class(); | |
task2Class.CreateImageFeed(); | |
} | |
} | |
public class Task3Runner : Runner | |
{ | |
protected override void DoTask(ScheduledTask task) | |
{ | |
vr task3Class = new Task3Class(); | |
task3Class.DestroyImageFeed(); | |
} | |
} | |
public class Task4Runner : Runner | |
{ | |
protected override void DoTask(ScheduledTask task) | |
{ | |
var task4Class = new Task4Class(); | |
task4Class.ProcessData(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment