Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading best practice

Tags:

c#

overloading

I have two static methods that I want to use for error handling. One of which passes the exception object and the other is just used if needing to report an error which would be a text based message (string errorMessage).

The code within the two methods is pretty much the same with the exception of how the message is build up and sent to a log file. How can I refactor this so that I'm not duplicating code?

public static void ReportError(Exception exceptionRaised, string reference, string customMessage, bool sendEmail)
{
    // get filename
    // check if logfile exists, blah, blah
    // build up message from exception, reference & custom message using string builder
    // save message
    // email error (if set)
}

public static void ReportError(string errorMessage, string reference, bool sendEmail)
{
    // get filename
    // check if logfile exists, blah, blah
    // build up message from errorMessage & reference string builder
    // save message
    // email error (if set)
}

Thanks.

like image 449
StuffandBlah Avatar asked Dec 02 '22 04:12

StuffandBlah


1 Answers

Seeing as all you're doing differently is building up a custom message in the first method, change your first method to pass the custom exception through the plain text error message method instead:

public static void ReportError(Exception exceptionRaised, string reference, 
    string customMessage, bool sendEmail)
{
    string errorMessage = BuildMessage(exceptionRaised, customMessage);
    ReportError(errorMessage, reference, sendEmail);
}

Disclaimer: Not entirely sure if this will work. It depends how you build up the error message.

EDIT:

Or you could add a third overload:

private static void ReportError(string completeException, bool sendEmail)
{
     // Do what needs to be done.
}

And then your methods could just both build up the exception message and pass that string and sendEmail boolean to the third overload.

like image 57
djdd87 Avatar answered Dec 25 '22 01:12

djdd87