Question

I am working on an application that has been edited by various programmers over the past few years and I have stumbled across a problem with using String Literals to access MenuItems.

For Example: in many places there is code like

mainMenu.MenuItems[1].MenuItems[0].Visible=true;

or

mainMenu.MenuItems["View"].MenuItems["FullScreen"].Visible=true;
  1. how do I change the Strings used to identify the MenuItem and catch all of the places that it is being used for access? The menus and menuitems are declared as public and are used throughout this large application

  2. What is the right way prevent the use of these magic indexes from being used. I forsee things being broken everytime a new item is added or the name is changed.

P.S. I have started using an enumerated dictionary approach in which every menuItem is paired with a key. but this still does not force other developers to use my implementation nor is it the most elegant solution to question 2

Était-ce utile?

La solution

Give each menu item a name in the WinForms designer (I assume), and then refer to it by that name.

enter image description here

Then just use this in your code:

menuExit.Visible = false;

If the menu items are added programmatically, do this:

class MyForm : Form
{
    private MenuItem menuExit;

    ...

        myMenu.Items.Add(menuExit = new MenuItem(...));

    ...
}

and then still access it by the menuExit name. The key to avoiding magic numbers and strings is to just keep a direct reference to whatever it is you want to refer to. As a bonus, you can now rename this vairable safely using F2.

Autres conseils

Romkyns answer is the correct one for this scenarion however if you do need to use string literals in your code I would alwasy keep them in public static classes such as:

public static class Constants
{
    public static class Menu 
    {
        public static readonly string FirstMenuName = "Menu 1";
        ...
    }

    public static class OtherCateogry
    {
        ...
    }
}

You can then access them by Constants.Menu.FirstMenuName.

As for definitively preventing other devs from using literals throughout code - you might have to make recourse to the Rod of Correction (sturdy metal ruler) ;).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top