Avoiding sub-type selection in view code
I have some code where t开发者_如何学JAVAhe model contains some classes like (vb.net pseudocode, but could be any OO language):
Enum AttributeType
Boolean
Date
String
End Enum
MustInherit Class Attibute
Must Override Function Type As AttributeType
End Class
Class BooleanAttribute: Attribute
Function Type As AttributeType
Return AttributeType.Boolean
End Function
End Class
And the view contains some code like:
Select Case AttributeType
Case Boolean
//Display checkbox control
Case Date
//Display date picker control
Case String
//Display textbox control
End Select
I don't really like the code in the view, for the hopefully obvious reasons (what happens when I get a new attribute type etc). My question is, how should I replace it?
I could easily add a method to the concrete classes, but that pollutes the model with UI stuff so that's a horrible idea.
I could move the select into a factory, but that seems to be just hiding the problem.
Can anybody advise a better approach?
If this is a single Case statement, I would just leave it as is.
If it is something that is done many times, you could create a helper method, which you send in all the controls and the helper method sets the correct control visible.
You could also do a for each over the Attribute Types, this may reduce the work required when adding new attribute types.
精彩评论