Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the Correct View for an Object Type

I've had this problem many times before, and I've never had a solution I felt good about.

Let's say I have a Transaction base class and two derived classes AdjustmentTransaction and IssueTransaction.

I have a list of transactions in the UI, and each transaction is of the concrete type AdjustmentTransaction or IssueTransaction.

When I select a transaction, and click an "Edit" button, I need to decide whether to show an AdjustmentTransactionEditorForm or an IssueTransactionEditorForm.

The question is how do I go about doing this in an OO fashion without having to use a switch statement on the type of the selected transaction? The switch statement works but feels kludgy. I feel like I should be able to somehow exploit the parallel inheritance hierarchy between Transactions and TransactionEditors.

I could have an EditorForm property on my Transaction, but that is a horrible mixing of my UI peanut butter with my Model chocolate.

Thanks in advance.

like image 777
James Thigpen Avatar asked Nov 18 '25 21:11

James Thigpen


1 Answers

You need to map your "EditorForm" to a transaction at some point. You have a couple options:

  • A switch statement...like you, I think this stinks, and scales poorly.
  • An abstract "EditorForm" property in base Transaction class, this scales better, but has poor seperation of concerns.
  • A Type -> Form mapper in your frontend. This scales fairly well, and keeps good seperation.

In C#, I'd implement a Type -> Form mapper like this:

Dictionary <Type,Type> typeMapper = new Dictionary<Type,Type>();
typeMapper.Add(typeof(AdjustTransaction), typeof(AdjustTransactionForm));
// etc, in this example, I'm populating it by hand, 
// in real life, I'd use a key/value pair mapping config file, 
// and populate it at runtime.

then, when edit is clicked:

Type formToGet;
if (typeMapper.TryGetValue(CurrentTransaction.GetType(), out formToGet))
{
    Form newForm = (Form)Activator.CreateInstance(formToGet);
}
like image 62
FlySwat Avatar answered Nov 21 '25 09:11

FlySwat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!