patterncsharpModerate
This code looks really repetitive. Any way to shorten it?
Viewed 0 times
thisreallyanywayshortenrepetitivelookscode
Problem
I have something like this in my program:
As I increase the amount of tools this list will only get longer. Is there something I could do to shorten it?
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:
-
If tspXxxx cannot be retrieved from the sender directly, use another HashMap to map senders to tspXxxx objects.
-
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.