Skip to main content
Spurious Logic

This is why we have switch statements

I came across a head-slappingly dumb bug earlier with a generic method. Which only occurred for Task types A or B. If you spot it, give yourself a "my isn't that obvious" cookie.

public List GetUserTasks(int userId) where T : Task { IEnumerable result = null; if (typeof(Task_A) == typeof(T)) { result = (IEnumerable)this.taskRepository.GetTask_A(participantId, clientId); } else if (typeof(Task_B) == typeof(T)) { result = (IEnumerable)this.taskRepository.GetTask_B(participantId, clientId); } if (typeof(Task_C) == typeof(T)) { result = (IEnumerable)this.taskRepository.GetTask_C( participantId, clientId); } else if (typeof(Task_D) == typeof(T)) { result = (IEnumerable)this.taskRepository.GetTask_D(participantId, clientId); } else { throw new ApplicationException("Unknown task type requested : " + typeof(T).ToString()); } return result.ToList(); }

Yes I know this is not the ideal way to handle generics but as some point, different stored procedures must be called for different classes and I think it's better to make that distinction in the service rather than the repository layer. You're repositories should just be calling stored procs and handling the returning values.

Of course you can't use a switch statement here because switch statements require constant values... So the only fix here was to add in that missing else and update the unit tests to cover the method correctly.