Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining methods

In my app I have a lot of copy and paste code that is exactly the same and performs exactly the same function (button click events and the like). These redundant code live in the code-behind of many of my pages. So I decided to reduce the code duplication and to move these methods into a class file and only make a call to them from the code-behind pages.

Here is an example of a button click event in my code behind calling the methods from a class file:

#region DELETE selected users - button

protected void btnDeleteSelected_Click(object sender, EventArgs e)
{
    try
    {
        UserGvUtil.DeleteSelectedUsersAndProfiles(GridView1, Msg);
    }
    catch (Exception ex)
    {
        UserGvUtil.ExceptionErrorMessage(Msg, ex);
    }
    finally
    {
        UserGvUtil.RefreshGridView(GridView1);
    }
}

#endregion

Can I combine this try/catch block into yet another method and move it to the same class file? So, the only thing I have in the click event is a single line of code.

Does it make sense to do this? Not sure why, but I would like to have my code behind files as clean and simple as possible so I can make all the edits in a single place.

Sorry if I make no sense. I'm just learning about classes and methods and it floods my head with lots of ideas.

like image 221
Scott W Avatar asked Sep 25 '26 11:09

Scott W


2 Answers

You can move the stuff inside the try block into an anonymous delegate that you pass to a shared method that has a try/catch. You really don't need to put the refresh into the finally, though. In fact, I would think you would only want to run it if the try block succeeds.

like image 154
Steven Sudit Avatar answered Sep 28 '26 01:09

Steven Sudit


You can wire the event handlers manually.

btnDeleteSelected1.Click += Events.BtnDeleteSelected_Click;
btnDeleteSelected2.Click += Events.BtnDeleteSelected_Click;
...
btnDeleteSelected3.Click += Events.BtnDeleteSelected_Click;

public static class Events
{
  public static BtnDeleteSelected_Click(object sender, EventArgs e)
  {
     ...
  }
}

Edit (for downvoters: ???) The code will give you a one liner and you won't have to worry about writing custom events when they are all the same.

Also, if the utility methods have the same signature you could have a generic method:

public void ExecuteGvMethod(Action<GridView, string> gvMethod, GridView gv, string msg)
{
    try
    {
        gvMethod(gv, msg);
    }
    catch (Exception ex)
    {
        UserGvUtil.ExceptionErrorMessage(msg, ex);
    }
    finally
    {
        UserGvUtil.RefreshGridView(GridView1);
    }
}

And in code:

public static class Events
{
  public static BtnDeleteSelected_Click(object sender, EventArgs e)
  {
    ExecuteGvMethod(UserGvUtil.DeleteSelectedUsersAndProfiles, (GridView)sender, "hi of whatever");
  }
}
like image 45
Jaroslav Jandek Avatar answered Sep 27 '26 23:09

Jaroslav Jandek