Need Help Spotting that Hard to Test Code?


I’m a big fan of Jon Lam’s Vibrant Ink Visual Studio theme. Here’s why: If you look at the syntax highlighting in the following code, you’ll see some yellow text. In this theme, or any any other theme that does it well, you’ll notice class names stand out a bit on their own. Referencing a class name means you’re probably either creating a new object or referencing a static function or property. Both of these make for hard to test code. Code that is hard to test is brittle. Apply Murphy’s Law and you’re in trouble.

public class CustomerNotifier
{
private readonly EmailService emailService;

public CustomerNotifier()
{
emailService =
new EmailService();
}

public void SendNotification(IUser user, string subjectText, string messageText)
{
if(user.Subscriptions().Contains(this))
{
MailMessage mailMessage = new MailMessage("customerService@company.com",
user.Email, subjectText, messageText);
emailService.SendTo(user, mailMessage);
}
}
}

If I want to test whether the SendTo message was called on the email service when the instance is contained in the user’s subscriptions and NOT called when the user isn’t subscribed to it. I can’t really think of a good way to do so.

Time to Redo This a Bit

My theme settings are telling me that EmailService and MailMessage should be abstracted. This is because they’re “yellow”. Not really the reason, but those are what I see as flags for improvement. Instead of newing-up a MailMessage, I’m going to create my own abstraction. I’m also going to inject the EmailService (as an abstraction) into the constructor. Later on, we can make assertions on it using a mocked object.

public class CustomerNotifier
{
private readonly IEmailService emailService;

public CustomerNotifier(IEmailService emailService)
{
this.emailService = emailService;
}

public void SendNotification(IUser user, IMailMessage mailMessage)
{
if(user.Subscriptions().Contains(this))
{
mailMessage.From =
"customerService@company.com";
emailService.SendTo(user, mailMessage);
}
}
}

This helps me quickly identify areas of my code that seem to be designed poorly. When I see a lot of whatever color my class names are, I see areas that can be improved. This code is much easier to test now.

Ongoing Maintenance & Debt Reduction