Switch vs Polymorphism when dealing with model and view
- by Raphael Oliveira
I can't figure out a better solution to my problem. I have a view controller that presents a list of elements. Those elements are models that can be an instance of B, C, D, etc and inherit from A. So in that view controller, each item should go to a different screen of the application and pass some data when the user select one of them. The two alternatives that comes to my mind are (please ignore the syntax, it is not a specific language)
1)
switch (I know that sucks)
//inside the view controller
void onClickItem(int index) {
A a = items.get(index);
switch(a.type) {
case b:
B b = (B)a;
go to screen X;
x.v1 = b.v1; // fill X with b data
x.v2 = b.v2;
case c:
go to screen Y;
etc...
}
}
2) polymorphism
//inside the view controller
void onClickItem(int index) {
A a = items.get(index);
Screen s = new (a.getDestinationScreen()); //ignore the syntax
s.v1 = a.v1; // fill s with information about A
s.v2 = a.v2;
show(s);
}
//inside B
Class getDestinationScreen(void) {
return Class(X);
}
//inside C
Class getDestinationScreen(void) {
return Class(Y);
}
My problem with solution 2 is that since B, C, D, etc are models, they shouldn't know about view related stuff. Or should they in that case?