rulururu

post The Aaron and Mike Show #3

November 6th, 2008

Filed under: The Aaron and Mike Show — mike hall @ 5:17 pm

Our third installment is signed, sealed and delivered. Despite a temporary change of cohosts and change of location, it… well… we got through it. That’s all that counts. Check it out!

Streaming live video by Ustream

post Decoupling Your Classes

November 6th, 2008

Filed under: coding, patterns, programming — mike hall @ 5:17 pm

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?

ruldrurd

Powered by WordPress, Theme based off the "I'm Okay" theme by Laurentiu Piron

Creative Commons License This work is licensed under a Creative Commons Attribution 3.0 United States License.


Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.