Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding magic strings and numbers

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

like image 342
jth41 Avatar asked Sep 18 '26 22:09

jth41


1 Answers

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.

like image 57
Roman Starkov Avatar answered Sep 21 '26 11:09

Roman Starkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!