0

In my app, we have master page which has some common features like export to excel, pdf etc.

On content page, I have TabContainer with multiple tabs.

When I run option like export to excel, Master page calls exportExcel function on content page. Based on active tab, I run different logic to export the data. Fields are different on each tab so separate logic is needed.

 var activeTab = TabContainer.ActiveTab;
if (activeTab == abc_Tab)
{
//some logic
}
else if (activeTab == def_Tab)
{
//some logic
}
else if (activeTab == ghi_Tab)
{
//some logic
}
else if (activeTab == jkl_Tab)
{
//some logic
}

This code is working Perfectly fine. The problem is, this if-else logic is repeatative with every master page feature. If I add new feature like export to csv, ExportCsv functiona will also have this if-else condition. This is not limited to export functionality. sometimes, I need to pass some data/parameter also and based on active those, those data/parameter interpret differently.

Is there any better way to handle this?

Abhash786
  • 881
  • 2
  • 24
  • 53

1 Answers1

1

I would recommend to use Strategy pattern to wrap/hide all this stuff. https://www.dofactory.com/net/strategy-design-pattern

Your can use a dictionary with export logic implementation and use tab name as key to retreive the implementation logic.

Dictionary<string, ExportLogicService> tabExportLogicDictionary= new Dictionary<string, ExportLogicService>();
// constructor
public YourUI()
{
  // Initialize your dictionary
  tabExportLogicDictionary.Add("abc_Tab", new abcTabExportLogic());
  ...
}

Where:

public abstract class ExportLogicService
{
    public abstract void ExportData();
}

public class abcTabExportLogic: ExportLogicService
{
    public override void ExportData()
    {
        // do something...
    }
}

public class ExportService
{
    ExportLogicService exportService;
    // Constructor
    public ExportService(ExportLogicService exportService)
    {
        this.exportService= exportService;
    }
    public void ExportMyData()
    {
        exportService.ExportData();
    }
}

And when it's time to export the data, then do next:

var tabName = TabContainer.TabPages[TabContainer.SelectedIndex].Name.ToString(); //get your tab name
var exportLogic = tabExportLogicDictionary[tabName]; //you can add verification before if needed
exportService = new ExportService(exportLogic);
exportService.ExportMyData();
Jivopis
  • 121
  • 11