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

Too many loops in Drawing App

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

Problem

I have a method that has a lot of loops:

```
private void update(double depth)
{

Console.WriteLine("update with level " + depth);

this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(delegate()
{

List grids = new List();

Dependencies.Children.Clear();

Grid g = new Grid();
//Canvas.SetZIndex(g, 100);
g.Width = 50;
g.Height = 50;
g.Tag = focus;

Ellipse e = new Ellipse();
e.Width = 50;
e.Height = 50;
e.Fill = Brushes.Red;
if (depth == 1)
{
Canvas.SetTop(g, 163);
}
else if (depth == 2)
{
Canvas.SetTop(g, 108);
}
else if (depth == 3)
{
Canvas.SetTop(g, 81);
}
else if (depth == 4)
{
Canvas.SetTop(g, 65);
}
else if (depth == 5)
{
Canvas.SetTop(g, 54);
}
else if (depth == 6)
{
Canvas.SetTop(g, 46);
}
Canvas.SetLeft(g, 500);

g.Children.Add(e);

Viewbox box = new Viewbox();
box.Width = e.Width;
box.Height = e.Height;

TextBox txt = new TextBox();
txt.Text = focus.getName();
box.Child = txt;
txt.Background = Brushes.Transparent;
txt.BorderBrush = Brushes.Transparent;

g.Children.Add(box);

grids.Add(g);

List list = new List();

list = focus.getInvocations();

int counter = 1;
foreach (SourceFile sf in list)
{
Grid g1 = new Grid();
//Canvas.SetZIndex(g, 101);
g1.Width = 50;
g1.Height = 50;

Solution

This code...

if (depth == 1)
{
    Canvas.SetTop(g1, 163);
}
else if (depth == 2)
{
    Canvas.SetTop(g1, 108);
}
else if (depth == 3)
{
    Canvas.SetTop(g1, 81);
}
else if (depth == 4)
{
    Canvas.SetTop(g1, 65);
}
else if (depth == 5)
{
    Canvas.SetTop(g1, 54);
}
else if (depth == 6)
{
    Canvas.SetTop(g1, 46);
}


Could be better implemented using an array...

int[] values = new [] { 0, 163, 108, 81, 65, 54, 46  }


Or Dictionary...

var values = new Dictionary() { { 1, 163 }, { 2, 108 }, { 3, 81 }, { 4, 65 }, { 5, 54 }, { 6, 46} };


This way you could simple say

Canvas.SetTop(g1, values[depth])

Code Snippets

if (depth == 1)
{
    Canvas.SetTop(g1, 163);
}
else if (depth == 2)
{
    Canvas.SetTop(g1, 108);
}
else if (depth == 3)
{
    Canvas.SetTop(g1, 81);
}
else if (depth == 4)
{
    Canvas.SetTop(g1, 65);
}
else if (depth == 5)
{
    Canvas.SetTop(g1, 54);
}
else if (depth == 6)
{
    Canvas.SetTop(g1, 46);
}
int[] values = new [] { 0, 163, 108, 81, 65, 54, 46  }
var values = new Dictionary<int,int>() { { 1, 163 }, { 2, 108 }, { 3, 81 }, { 4, 65 }, { 5, 54 }, { 6, 46} };
Canvas.SetTop(g1, values[depth])

Context

StackExchange Code Review Q#9, answer score: 60

Revisions (0)

No revisions yet.