Search code examples
c#coding-styleidiomssolid-principles

Coding Standards for button click event


I'm trying to follow good coding standards when attaching code to the default button click event. Two options are: Include several lines of code within the Click event handler or include a method that ultimately does same thing as those lines of code.

What are software design principles, or the concrete reasoning behind why I would use one way or the other?

[additionally, it's an existing standard winforms application that is just getting extended a bit.]

Option A:

private void btnExport_Click(object sender, EventArgs e)
{
    var FileName = getFileName(reportPrefix);

    if (fileName == null)            
    {
        return;
    }

    SaveFile(fileName, QueryString);
}

Option B:

private void btnExport_Click(object sender, EventArgs e)
{
    DoExport();           
}


private void DoExport()
{
    var FileName = getFileName(reportPrefix);

    if (fileName == null)            
    {
        return;
    }

    SaveFile(fileName, QueryString);

}

Solution

  • I will recommend for option B for following reasons:

    1. Separation of Concern: The code that is handling the event (EventHandler) or delegate is Separated from the Actual implementation logic that does the actual work and is encapsulated in another method.

    2. The intent of method DoExport is clear from it's name. If Someone read your code, it would be interpreted as

      Option B: "When button is clicked Do export."
      Option A: "When button is clicked read the file name, if fileName is empty then return, else Save the file."

      Which sounds easier to Read? For Readability purpose Option B provided a clear and concise way of representing your intentions.

    3. If you decide to change the button to another control like anchor, linkButton, Label or any other control, you don't need to bind the event handler with the implementation details. Like the DoExport method shouldn't rely on the EventArgs' or thesender` objects.

    4. In the future, the Export functionality (DoExport) needs to be called from other places in your code. Then, you can easily call the DoExport Method.

    5. Testing: If you have this method as public and you want to test it. It is much easier to test the method rather than writing code to raise an event and then test the functionality.