"Chris Fink" <no****@chrisfink.com> wrote in message
news:eN**************@TK2MSFTNGP12.phx.gbl...
I have a the requirement for a class to alert via an email message when an
error occurs. In this main class, I have wrapped the main logic into a try
catch statement. When an error occurs, inside of the catch statement a
call to an alert class is invoked which in turn sends an email with the
error message. What would be the preferred design approach to solve this
requirement?
Factory Method and simple delegation comes to mind.
My original thought is to create an interface for the AlertAgent which
will contain an Alert method.
yep
The main class would then implement this interface, requiring an Alert
method.
I disagree with this part. The main class would not 'implement' this
interface. A concrete 'EmailAlertAgent' class would implement the
interface. The main class would call a factory to return an object that
implements the interface. (at first, this factory method will be really
simple, because it will return an 'EmailAlertAgent' object.) The main class
would then simply call the object's Alert method. In a simple example like
this, I'd place the factory method as a static method in a seperate class in
the same namespace as your interface.
So code looks like this: (Caveat: air code... I use tools a lot, so my air
code is sloppy. I'm trying to illustrate...)
namespace MyCompany.Alert.Agent
{
public interface AlertAgent
{
public bool Alert(Exception excp, OtherAlertData otherdata);
}
public class EmailAlertAgent : AlertAgent
{
public bool Alert(Exception excp, OtherAlertData otherdata)
{
// implement the notification here. Use config settings or
a database to allow thing like the 'TO' line to be readily changed.
}
}
public class AlertFactory
{
public static AlertAgent GetAgent()
{
// for now, this is simple. In the future, you can have this
module check the config file to see if different
// apps would want to use a different alert agent, or if the
user wants to use more than one agent, etc.
return new EmailAlertAgent();
}
}
}
// The point of this exercise is that the code in this main class doesn't
change,
// no matter what changes you need to make to the structure of alerts.
namespace MyCompany.Stuff.Gets.Done
{
public class MainClass
{
public void MainMethod()
{
try
{
// do something hazardous and useful here
}
catch (Exception ex)
{
OtherAlertData ad = new OtherAlertData('useful param
1', 'useful param 2');
AlertAgent agent = AlertFactory.GetAgent();
agent.Alert(ex, ad);
}
}
}
}
--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik
Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
--