Similar event handlers for buttons I have 3 simple similar event handler functions that I would like to refactor. Any suggestions?

private void btnBuildingList_Click(object sender, EventArgs e)
    {
        selectedExportType = (int)ExportType.Building;
        path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-BuildingList.csv";
        Export();
    }

    private void btnOwnerList_Click(object sender, EventArgs e)
    {
        selectedExportType = (int)ExportType.Persons;
        path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-OwnerList.csv";
        Export();
    }

    private void btnFacts_Click(object sender, EventArgs e)
    {
        selectedExportType = (int)ExportType.Facts;
        path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-FactsData.csv";
        Export();
    }
You can use an Extract Method refactoring to get rid of the duplicate code:

private static string GetExportFilePath(string csvFilePath, DateTime date, string fileSuffix)
{
    return string.Format("{0}{1:yyyy-MM-dd}-{2}.csv", csvFilePath, date, fileSuffix);
}

I would add those selectedExportType and path variables as parameters to the Export() method. I hope they are not used anywhere. It is usually pretty subjective whether to add something as method parameters or leave it as class member, but here I would definitely pass them as parameters. I assume this class is a “View” since you have button click event handlers, and I also tend to move such methods out from the views.


If we use these two ideas, your event handlers would be simplified to:

private void btnBuildingList_Click(object sender, EventArgs e)
{
    var path = GetExportFilePath(csvFilePath, datDate.DateTime, "BuildingList.csv");
    Export((int)ExportType.Building, path);
}

private void btnOwnerList_Click(object sender, EventArgs e)
{
    var path = GetExportFilePath(csvFilePath, datDate.DateTime, "OwnerList.csv");
    Export((int)ExportType.Persons, path);
}

private void btnFacts_Click(object sender, EventArgs e)
{
    var path = GetExportFilePath(csvFilePath, datDate.DateTime, "FactsData.csv");
    Export((int)ExportType.Facts, path);
}