I hava a base type (A) which has two derivatives (B and C). The base type is not abstract. So, I have three objects.
The only difference between B and C is that they both have one extra different property:
- B.Foo
- C.Bar
Now I have conditions like this in my code:
if(myObject is B)
myDatabindB.DataSource = ((B)myReport).Foo);
else if(myObject is C)
myDatabindC.DataSource = ((C)myReport).Bar);
and in another method:
pnlSomePanel.Visible = myObject is B;
pnlSomeOtherPanel.Visible = myObject is C;
But you can imagine that when there’s a new type I have to update all my if-else statements. This violates a lot of OO principles.
But the problem is that I can’t think of a nice and clean solution to solve this issue.
Do you have a suggestion / idea to solve this problem?
EDIT:
If it matters, I am using the MVP pattern.
First, it’s good that you asked this with only three items–it makes fixing problems much faster :). Your code’s very generic, so I can only offer generic solutions.
The big goal here is to increase the encapsulation of classes A, B, and C–to make sure that anything relevant to A, B, or C is stored within those classes and not moved to, say, if-statements elsewhere.
We can move the logic for figuring out what the correct datasource is from the Controller (which is doing your binding) to your report. This method’s name should be descriptive, like GetReportSubjectLine().
This code will be reusable if you ever want to make different UI’s that still need this type of information from your report to generate whatever graphical view you’re generating.
There’s no good way around the second problem you presented. We could always move the panel visibility into the reports too, but that increases coupling–how much one class is tied to another–way too much. Your reports should not be tied to a specific view.
The best solution is to add another layer of indirection–in this case, an intermediary class to handle the logic of what panels to make visible when. This way your controller doesn’t have to bear the responsibility of managing panel visibilities itself.
Hope this helps!