0

For my WPF view, I have several objects that implement a single interface for display purposes. When one is selected, I want to call a certain method based on the type and options chosen on the view. I already have Overloads available for each type of object. I attempted using a generic method, but it proved that the objects were too different to be useable.

I am trying to avoid control coupling with large if statements for maintainability purposed.

Did I go wrong by using the singular interface, or is there an interesting maintainable way of doing this?

I have a datagrid that contains a collection of IDisplayableObject.

public interface IDisplayableObject
{
    string Name { get; set; }
    string ID { get; set; }
}

Right now, I cast as the first answer.

 public void ExportDashed(string path, IDisplayableObject folder)
    {
        if (folder is TestFolder)
        {
            IndentationTraverse(folder as TestFolder);
        }
        else if (folder is UserStory)
        {
            IndentationTraverse(folder as UserStory);
        }
        _excelManipulator.Save(path);
    }

I want to avoid the if statements. For this case, I usually use a dictionary mapped to an Action, but I also have another method of

    public void ExportShiftingColumns(string path, IDisplayableObject folder)
    {
        if (folder is TestFolder)
        {
            ColumnShiftTraverse(folder as TestFolder);
        }
        else if (folder is UserStory)
        {
            ColumnShiftTraverse(folder as UserStory);
        }
        _excelManipulator.Save(path);
    }

So, I need to make the action, Export Dashed or Export Shifting Columns, then I need to decide which type to export.

You can see from the code, duplication is not a good thing and I want to avoid it as much as possible. For this application, it is not that big of a deal but more for my personal learning.

tylerjgarland
  • 643
  • 6
  • 19

1 Answers1

1

Maybe not the most elegant solution, but try

if ( myObject as IInterface1 != null )
    ((IInterface1)myObject).Method1();
else if ( myObject as IInterface2 != null )
    ((IInterface2)myObject).Method2();

and so on...

sotn0r
  • 109
  • 6
  • maybe i got the wrong idea what you are trying to achieve.. as @Trevor Pilley suggested, can you post an example of your code? – sotn0r Feb 20 '12 at 10:54