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

Go Back with More Detail

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

Problem

I have a Back function, and it is growing. I also think this is terrible, but I don't seem to get how it can be improved:

`public void GoBack()
{
NavButtonUsed = true;

Forward.Insert(0, Back[0]);
Back.RemoveAt(0);

if (Back[0].Title.StartsWith(" ") && CurrentItem.Menu != Back[0].Menu)
{
switch (Back[0].Menu)
{
case Menus.WSOneNote:
CurrentItem = ItemList[0];
break;

case Menus.WSMainMenu:
CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("MainMenu"), typeof(WindowsData.MainMenu), Menus.WSMainMenu))];
break;

case Menus.WSTextMenu:
CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TextMenu"), typeof(WindowsData.TextMenu), Menus.WSTextMenu))];
break;

case Menus.WSTextBlockMenu:
CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TextBlockMenu"), typeof(WindowsData.TextBlockMenu), Menus.WSTextBlockMenu))];
break;

case Menus.WSTableMenu:
CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TableMenu"), typeof(WindowsData.TableMenu), Menus.WSTableMenu))];
break;

case Menus.WSTableCellsMenu:
CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("TableCellsMenu"), typeof(WindowsData.TableCellsMenu), Menus.WSTableCellsMenu))];
break;

case Menus.WSDrawMenu:
CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString("DrawMenu"), typeof(WindowsData.DrawMenu), Menus.WSDrawMenu))];
break;

case Menus.WSDrawnItemsMenu:
CurrentItem = ItemList[ItemList.IndexOf(MenuItem.CreateMenuItem(resourceFile.GetString(

Solution

After Ben Rudger's suggestion to use a Dictionary, I realized that if the menu is closed, there is only one instance of a MenuItem in ItemList with the matching Menus.Value. Because of this, all I have to do is iterate over ItemList until I find that matching value, choose that value, and exit the loop, so GoBack becomes this:

public void GoBack()
{
NavButtonUsed = true;

Forward.Insert(0, Back[0]);
Back.RemoveAt(0);

if (Back[0].Title.StartsWith(" ") && CurrentItem.Menu != Back[0].Menu)
{
foreach(MenuItem mi in ItemList)
{
if (mi.Menu == Back[0].Menu)
{
CurrentItem = ItemList[ItemList.IndexOf(mi)];
break;
}
}
}

CurrentItem = ItemList[ItemList.IndexOf(Back[0])];
NavButtonUsed = false;
}


If the menu is open, we do not use the loop, but it still would work because the menu is still the first instance of MenuItem with its specific Menus.Value in the list.

Context

StackExchange Code Review Q#78902, answer score: 5

Revisions (0)

No revisions yet.