dimanche 10 juillet 2016

Code design to avoid downcasting and propagate correct concrete type to the front end

I am facing a code design issue, and although I'm sure someone else must have faced this before I haven't managed to find the answer despite hours of googling...

I have a web page made of a list of orders at the top, and when the user clicks on one order a form is displayed below, but this form can differ depending on the ordered item. My problem is quite simple really: when it comes to loading the item from the DB I only have an ID, so I don't know what type of item it is, and most importantly I don't know how to design my code to avoid any downcasting so that the appropriate item view is displayed.

Option 1: In my DB provider have a "Item LoadItem(int id)" function: the only way I found to display the appropriate item view is to somewhere check the concrete type of Item and use downcasting (yes, I know, that hurts). Something's telling me I could use polymorphism here, but I'm not sure how as I want to keep the items front-end agnostic. Should I use the Visitor pattern here?

Option 2: - In my DB provider have a "ItemType GetItemType(int id)", with ItemType being an enum - Have the Controller call that function, and depending on the result call the appropriate LoadItem function e.g "Table LoadTableItem(int id)" for instance. That solution doesn't seem very elegant to me, as somewhere in the code I end up with a "switch...case" statement on the ItemType value.

I hope this is all clear, thank you in advance for yout help!

Aucun commentaire:

Enregistrer un commentaire