Underscore as variable name in Java. Why?

wageoghe :

We are going through the process of upgrading our product codebase from Java 8 to Java 12. One problem we found was that our code has a number of cases where the underscore character ( _ ) is used as a variable name, which is no longer allowed (apparently since Java 9). This is legacy code, so I don't really know why it was written like this in the first place. It seems like, in the vast majority of cases, there is a method defined (named _ ) to retrieve a resource string by name. For example, one instance of such a method looks like this:

private static String _(String key)
{
    return PTR.getResources ().getStringProperty (key);
}

The method is used like this:

JFileChooser chooser = m_directory.getFileChooser ();
chooser.setDialogTitle (_("chooser.title"));
chooser.setFileFilter (ExtensionsFileFilter.withFullDescription (_("chooser.shp"), ".shp"));
chooser.setFileSelectionMode (JFileChooser.FILES_AND_DIRECTORIES);
addProperty (_("labels.dir"), m_directory);

We are in the process of renaming the _ methods. However, I was curious about why this pattern was used so much in our code. Was this a popular pattern at some point? Was it popular when using a certain technology (Swing)? All of my Googles so far have only found hits for the fact that variables can no longer be named _, but no explanation about why this might have been done in the first place. The original developers are no longer around, so I can't ask them.

Does anyone have any ideas?

I don't think this is a duplicate of the suggested question. That question is tagged "c" whereas mine is tagged "java". Also, the accepted answer for that question says the the _ function is a predefined function provided by gettext. That does not specifically apply in my as the _ functions I was asking about are actually defined in our java codebase. Having said that, the context of the suggested question and some of the info posted here seems to indicate a relationship. It sounds like the _ function/method can be commonly be understood to be used when retrieving localizable string resources.

Jb31 :

I can't speak for your code, but I know the _ method as an alias used for i18n methods (like in gettext or laravel). I would guess that the underscore is used to prevent littering the whole code with method names like GetTranslationFor() as it is often used.

Guess you like

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