Avoiding magic strings and numbers

陌路散爱 提交于 2019-12-06 07:11:57

问题


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


回答1:


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

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.




回答2:


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) ;).



来源:https://stackoverflow.com/questions/11099876/avoiding-magic-strings-and-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!