Why do we use KeyEvent.VK_? instead of simply using the character

feel free :

Suppose we want set a mnemonic for a menu item, and we want it be 'c'. I notice in almost all codes they write it as:

menuitem.setMnemonic(KeyEvent.VK_C);

I know that we can write it like this:

menuitem.setMnemonic('c');

However, the first variant seems to be more common. Why is that? Why don't we just use simple characters instead of something like KeyEvent.VK_C? What advantage have the first code over the second?

Adam :

In the second example, the character 'c' is a "magic" character. It happens to be the right value now, but it may not in the future. If it ever does change, somebody would have to go find all the places where 'c' was typed and fix it. If a constant expression is used, like in the first example, only a single place needs to change.

You might think "but of course it won't change, it will always be just 'c'". There are definitely times where constants can be overkill. For example if the magic value is used only once, or is a value that will 100% never change. But consider if it turns into 'c\special-character' or something. It is just safer, and a best practice, to use constants in place of magic strings or characters.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309776&siteId=1