I'm actually reorganizing a piece of code. what I want to do is initialize the Task object using the TaskArgument object. let s say "TaskArgument" is abstract, and "Task" implements the "OnEnterTask (TaskArgument args)" method and is sealed (for some special behavior of an existing system that is beyond the scope).
old code:
public sealed class Task : SomeSystemBaseTask { private int accessMe; private int meToo; public void OnEnterTask(TaskArgument args) { if (args is SimpleTaskArgument) { accessMe = ((SimpleTaskArgument)args).uGotIt; meeToo = 0; } else if (args is ComplexTaskArgument) { accessMe = ((ComplexTaskArgument)args).uGotItValue * ((ComplexTaskArgument)args).multiplier; meToo = ((ComplexTaskArgument)args).multiplier - 1; } } }
What would be the best practice to avoid type checking? my first thought about stupud was:
public abstract class TaskArgument { internal public abstract Initialize(Task args); } public class SimpleTaskArgument : TaskArgument { public int uGotIt = 10; internal public Initialize(Task task){ task.accessMe = uGotIt; } } public class ComplexTaskArgument : TaskArgument { public int uGotItValue = 10; public int multiplier = 10; internal public Initialize(Task task){ task.accessMe = uGotItValue*multiplier; task.meToo = multiplier - 1; } } public sealed class Task : SomeSystemBaseTask { public int accessMe; public int meToo; public void OnEnterTask(TaskArgument args){ args.Initialize(this); } }
but then my "accessMe" is public, and the "Initialization" method works only with the "Task". so I moved typechecking to another place (in the future). is there any best practice or good design idea.
... the "inner public" ... mmhhmm?
another crazy idea was the inner class, but I don't like it, and it makes such a simple case more complicated or not:
public abstract class TaskArgument { internal public abstract Initialize(ITaskWrapper wrapper); } public class SimpleTaskArgument : TaskArgument { ... } public class ComplexTaskArgument : TaskArgument { ... } public interface ITaskWrapper { public int AccessIt { set; get; } ... } public sealed class Task : SomeSystemBaseTask { private int accessMe; ... class TaskWrapper : ITaskWrapper { ... } public void OnEnterTask(TaskArgument args){ args.Initialize(new TaskWrapper(this)); } }
where is the best place to initialize when it is based on the given type of "TaskArgument"?
kindly excuse my poor knowledge of english
Hi Mo
source share