Decoupling Your Classes
November 6th, 2008
Don’t you hate it when you go back to some old code and then just want to vomit? I had an experience like that recently. I went into the options form of my pet project Bitter and found this gem:
public OptionsForm : Form
{
private void ApplyTheme()
{
MainForm.GetInstance().UpdateColors();
}
}
Bleh! Oob! Ick! Seriously, what was I thinking? Right there, the options form is tied to the MainForm. Those two classes can’t be reused elsewhere without some rework. Not good. So how do you fix it? My first thought is usually interfaces. So then I came up with this:
interface IThemeable
{
void UpdateColors();
}
public OptionsForm : Form
{
public MyForm(IThemeable themeableParent)
{
m_themeableParent = themeableParent;
}private void ApplyTheme()
{
m_themeableParent.UpdateColors();
}
}
Ah… so much better. Now if the options form gets reused, it’s parent only needs to implement IThemeable and then I’m good to go. One other method I tend to use a lot (maybe even overuse) is the Observer Pattern. In the observer pattern, you have a subject that sends events, produces information, publishes data, or in whatever way has something that an observer of the subject wants. The subject can zero observers, one observers, or N observers. It doesn’t really care if someone is listening or not. Anyway, here is how I would solve this problem with the observer pattern:
interface IThemeObserver
{
void OnThemeChanged();
}interface IThemeSubject
{
void RegisterThemeObserver(IThemeObserver observer);
void OnThemeChanged();
}public OptionsForm : Form, IThemeSubject
{
public MyForm(IThemeObserver parent)
{
RegisterThemeObserver(parent);
}public void RegisterThemeObserver(IThemeObserver observer)
{
m_observers.Add(observer);
}public void OnThemeChanged()
{
foreach (IThemeObserver observer in m_observers)
{
observer.OnThemeChanged();
}
}private void ApplyTheme()
{
OnThemeChanged();
}
}
So those are my modus operandi. How do you fix similar problems?





[…] Decoupling Your Classes - Mike Hall Mike decouples his all too coupled classes, throwing in a design pattern here and there (well, here, not there) ‘ Don’t you hate it when you go back to some old code and then just want to vomit? I had an experience like that recently ‘ […]
November 7, 2008 @ 3:31 pm
[…] Decoupling Your Classes (Mike Hall) […]
November 8, 2008 @ 9:15 pm