Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One method for two different signatures

Tags:

c#

I have two methods which do exactly the same, but one accepts a PaintEventArgs class parameter while the other accepts a PrintPageEventArgs class parameter. This forces me to write two different methods which tends to be a little excessive for such a slight difference.

public static void DoAllTasks_Panel(PaintEventArgs e)
{
    // Commands...
}

public static void DoAllTasks_Print(PrintPageEventArgs e)
{
    // Commands...
}

I have tried to merge them into a single method using an EventArgs class parameter with no success, as follows:

public static void DoAllTasks(EventArgs e)
{
    // Commands...
}

Is there any possibility to merge them into a single method?

like image 424
codeaviator Avatar asked Dec 03 '25 09:12

codeaviator


2 Answers

If DoAllTasks_Panel and DoAllTasks_Print genuinely do the same thing, and only exist because of the need for two different signatures, then the standard approach is to create a third, private, method that does the work and have each call it:

public static void DoAllTasks_Panel(PaintEventArgs e)
{
    DoCommands();
}

public static void DoAllTasks_Print(PrintPageEventArgs e)
{
    DoCommands();
}

private static DoCommands()
{
    // Commands...
}

This way you are separating concerns and satisfying DRY (do not repeat yourself) principles nicely: you have individual event handler methods and a third method that does all the common work.

like image 151
David Arno Avatar answered Dec 05 '25 21:12

David Arno


You can write a third private method that takes the values you care about from those EventArgs as parameters, and then make those two methods one-liners that just call the third method.

like image 34
fmt Avatar answered Dec 05 '25 23:12

fmt