I'm practicing C# on Testdome.com, I solved the coding exercise (AlertService) below but still not convinced by the purpose of point 3 and 4:
Refactor the AlertService and AlertDAO classes:
1- Create a new interface, named IAlertDAO, that contains the same methods as AlertDAO.
2- AlertDAO should implement the IAlertDAO interface.
3- AlertService should have a constructor that accepts IAlertDAO.
4- The RaiseAlert and GetAlertTime methods should use the object passed through the constructor.
This is the code I write, I added the constructor and the interface that AlertDAO implements, at the end The Compilation was OK but I need to know if this is the right way to solve it:
public class AlertService
{
private readonly AlertDAO storage = new AlertDAO();
//Constructor
public AlertService(IAlertDAO alert)
{
storage = (AlertDAO)alert;
}
public Guid RaiseAlert()
{
return this.storage.AddAlert(DateTime.Now);
}
public DateTime GetAlertTime(Guid id)
{
return this.storage.GetAlert(id);
}
static void Main(string[] args)
{
IAlertDAO alertDao = new AlertDAO();
AlertService alert = new AlertService(alertDao);
Guid id = alert.RaiseAlert();
Console.WriteLine(alert.GetAlertTime(id));
Console.ReadKey();
}
}
public class AlertDAO : IAlertDAO
{
private readonly Dictionary<Guid, DateTime> alerts = new Dictionary<Guid, DateTime>();
public Guid AddAlert(DateTime time)
{
Guid id = Guid.NewGuid();
this.alerts.Add(id, time);
return id;
}
public DateTime GetAlert(Guid id)
{
return this.alerts[id];
}
}
public interface IAlertDAO
{
Guid AddAlert(DateTime time);
DateTime GetAlert(Guid id);
}
storage) should be declared withIAlertDAOas well. Also, what is the main method doing there? It has no business being in a class dedicated to something else entirely.storageas anIAlertDAO.