避免魔术字符串和数字 [英] Avoiding magic strings and numbers

查看:311
本文介绍了避免魔术字符串和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我就已经在过去的几年中编辑各种程序员和我已经跨越了问题跌跌撞撞使用字符串字面访问的MenuItems一个应用程序的工作。



例如:在很多地方有像



  mainMenu.MenuItems [1] .MenuItems [0]。可见=真; 

  mainMenu.MenuItems [视图]的MenuItems [全屏]可见=真。; 




  1. 我如何改变字符串用来识别菜单项和捕捉所有它正用于访问的地方?菜单和菜单项被声明为公众和整个大的应用程序中使用


  2. 什么是正确的方式防止利用这些神奇的指标被使用。我预见的事情被打破每次添加新项目或更改了名称。




P.S。我已经开始使用,其中每个菜单项与一键配对的枚举字典方法。但是这仍然不能迫使其他开发人员使用我的实现,也不是最优雅的解决问题2


解决方案

每个菜单给出。项目中的WinForms设计师(我假设)的名称,然后用这个名字引用它。





然后,只需在代码中使用这样的:

  menuExit.Visible = FALSE; 






如果菜单项以编程方式添加,这样做

 类MyForm的:表格
{
私人菜单项menuExit;

...

myMenu.Items.Add(menuExit =新菜单项(...));


}



之后,还访问由 menuExit 名称。避免魔术数字和字符串的关键是只保留一个直接引用无论是你想参考。作为奖励,你现在可以重命名此vairable安全使用F2。


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

解决方案

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.

这篇关于避免魔术字符串和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆