DRY - Do you wrap the same logic in a method instead of writing it repeatedly whenever it's used?

Updated by Christian Morford-Waite [SSW] 3 months ago. See history

123
No component provided for introEmbed

DRY, which stands for ‘don’t repeat yourself,’ is a principle of software development that aims at reducing the repetition of patterns and code duplication in favor of abstractions and avoiding redundancy.

public class WarningEmail
{
//...
public void SendWarningEmail(string pFrom, string pTo, string pCC, string pUser, string pPwd, string pDomain)
{
//...
MailMessage sMessage = new MailMessage();
sMessage.From = new MailAddress(pFrom);
sMessage.To.Add(pTo);
sMessage.CC.Add(pCC);
sMessage.Subject = "This is a Warning";
sMessage.Body = GetWarning();
SmtpClient sSmtpClient = new SmtpClient();
sSmtpClient.Credentials = new NetworkCredential(pUser, pPwd, pDomain);
sSmtpClient.Send(sMessage);
//...
}
}
public class ErrorEmail
{
public void SendErrorEmail(string pFrom, string pTo, string pCC, string pUser, string pPwd, string pDomain)
{
//...
MailMessage sMessage = new MailMessage();
sMessage.From = new MailAddress(pFrom);
sMessage.To.Add(pTo);
sMessage.CC.Add(pCC);
sMessage.Subject = "This is a Error";
sMessage.Body = GetError();
SmtpClient sSmtpClient = new SmtpClient();
sSmtpClient.Credentials = new NetworkCredential(pUser, pPwd, pDomain);
sSmtpClient.Send(sMessage);
//...
}
}

❌ Figure: Bad example - Write the same logic repeatedly

public class WarningEmail
{
//...
public void SendWarningEmail(string pFrom, string pTo, string pCC, string pUser, string pPwd, string pDomain)
{
//...
EmailHelper.SendEmail(pFrom, pTo, pCC, "This is a Warning", GetWarning(), pUser, pPwd, pDomain);
//...
}
}
public class ErrorEmail
{
public void SendErrorEmail(string pFrom, string pTo, string pCC, string pUser, string pPwd, string pDomain)
{
//...
EmailHelper.SendEmail(pFrom, pTo, pCC, "This is an Error", GetError(), pUser, pPwd, pDomain);
//...
}
}
public class EmailHelper
{
public static void SendEmail(string pFrom, string pTo, string pCC, string pSubject, string pBody, string pUser, string pPwd, string pDomain)
{
MailMessage sMessage = new MailMessage();
sMessage.From = new MailAddress(pFrom);
sMessage.To.Add(pTo);
sMessage.CC.Add(pCC);
sMessage.Subject = pSubject;
sMessage.Body = pBody;
SmtpClient sSmtpClient = new SmtpClient();
sSmtpClient.Credentials = new NetworkCredential(pUser, pPwd, pDomain);
sSmtpClient.Send(sMessage);
}
}

✅ Figure: Good example - Put the same logic in a method and make it reusable

Acknowledgements

Adam Cogan
Related rules

Need help?

SSW Consulting has over 30 years of experience developing awesome software solutions.

We open source.Loving SSW Rules? Star us on GitHub. Star