I wanted to avoid the switch statement. I have over 30 document types. There is also a possibility I will need to add more document types moving forward. I would rather pass IDocument and have the type specified in the implementation of IDocument. Something else I forgot to mention was ProgressNoteViewModel, LabViewModel … all inherit from WorkspaceViewModel and all of the concrete implementation constructors take a type IPatient as parameter. I am also using Castle as my IoC container
I would want to refactor the code to something like
viewModel = new TreeViewModel(repository.GetPatientDocumentListing(IDocumentType);
this.DocTreeViewModel = viewModel;
//How would I then be able to instantiate the right ViewModel
//based on IDocumentType and also pass a object into the
//constructor that is not know at compile time
I have the following code:
switch (docType)
{
case "ProgressNotes":
viewModel = new TreeViewModel(repository.GetPatientProgressNotes());
this.DocTreeViewModel = viewModel;
ProgressNoteViewModel workspace = ProgressNoteViewModel.NewProgressNoteViewModel(_patient);
break;
case "Labs":
viewModel = new TreeViewModel(repository.GetPatientLabs());
this.DocTreeViewModel = viewModel;
LabViewModel workspace = LabViewModel.NewLabViewModel(_patient);
break;
}
this.Workspaces.Add(workspace);
this.SetActiveWorkspace(workspace);
Entirely untested:
Now your calling code is:
[4 edits since first post; keep seeing mistakes]
[Further Edit noting that you’re using Castle IOC]
In your Castle xml configuration, you could add (and I’m working on only a vague knowledge of Castle here)
Then you don’t need the ViewModelBuilderFactory, you can just replace
with
Now you don’t need your switch statement at all.
However, it’s worth noting that switches aren’t evil, they just smell bad and like all bad smells should be isolated from everything that smells good; that’s what the Factory pattern is intended to achieve.