HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

This code looks really repetitive. Any way to shorten it?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisreallyanywayshortenrepetitivelookscode

Problem

I have something like this in my program:

private void tspBrush_Click(object sender, EventArgs e)
    {
        currentTool = new Brush(tileLayers);

        UncheckToolstripButtons();

        tspBrush.Checked = true;
    }

    private void tspBucket_Click(object sender, EventArgs e)
    {
        currentTool = new Bucket(tileLayers);

        UncheckToolstripButtons();

        tspBucket.Checked = true;
    }

    private void tspCut_Click(object sender, EventArgs e)
    {
        currentTool = new Cut(tileLayers);

        UncheckToolstripButtons();

        tspCut.Checked = true;
    }


As I increase the amount of tools this list will only get longer. Is there something I could do to shorten it?

Solution

one way of shortening might be:

-
having a HashMap consisting of pairs of objects (sender) and Tools. This way you could look up the appropriate Tool for each sender in one single method like this:

HashMap hashMap = new HashMap( );

hashMap.put(sender1, new Brush(tileLayers));

// ...add the rest of the Tools
private void clickHandler(object sender, EventArgs e)
{
    currentTool = hashMap.get(sender);

    UncheckToolstripButtons( );
    tspBrush.Checked = true;
}


-
If tspXxxx cannot be retrieved from the sender directly, use another HashMap to map senders to tspXxxx objects.

Code Snippets

HashMap<object, Tool> hashMap = new HashMap<object, Tool>( );

hashMap.put(sender1, new Brush(tileLayers));

// ...add the rest of the Tools
private void clickHandler(object sender, EventArgs e)
{
    currentTool = hashMap.get(sender);

    UncheckToolstripButtons( );
    tspBrush.Checked = true;
}

Context

StackExchange Code Review Q#3938, answer score: 11

Revisions (0)

No revisions yet.