CodeSOD: Patterned After Success
Design patterns are more than just useless interview questions that waste everyone's time and annoy developers. They're also a set of approaches to solving common software problems, while at the same time, being a great way to introduce new problems, but enough about Spring.
For those of us that really want global variables back in our object oriented languages, the Singleton pattern is our go-to approach. Since it's the easiest design pattern to understand and implement, those new to design patterns tend to throw it in everywhere, whether or not it fits.
Andres once worked with a developer who not only was new and enthusiastic about design patterns, but didn't actually understand how to implement the Singleton pattern. Which is why Andres was getting null reference exceptions when trying to get an instance from this "singleton".
public class SingletonSmtpClient { private static SmtpClient _smtpClient; public SingletonSmtpClient(string host, string user, string password, bool ssl) { if (_smtpClient == null) { _smtpClient = new SmtpClient(); _smtpClient.Credentials = new System.Net.NetworkCredential(user, password); _smtpClient.EnableSsl = ssl; _smtpClient.Host = host; } } public static SmtpClient getInstance() { return _smtpClient; } }