Using underscores in Java variables and method names [closed]

Even nowadays I often see underscores in Java variables and methods, an example are member variables (like "m_count" or "_count"). As far as I remember, to use underscores in these cases is called bad style by Sun.

The only place they should be used is in constants (like in "public final static int IS_OKAY = 1;"), because constants should be all upper case and not camel case. Here, the underscore should make the code more readable.

Do you think using underscores in Java is bad style? If so (or not), why?


If you have no code using it now, I'd suggest continuing that. If your codebase uses it, continue that.

The biggest thing about coding style is consistency. If you have nothing to be consistent with, then the language vendor's recommendations are likely a good place to start.


sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs();

as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable();

Rules:

  1. Do what the code you are editing does
  2. If #1 doesn't apply, use camelCase, no underscores

I don't think using _ or m_ to indicate member variables is bad in Java or any other language. It my opinion it improves readability of your code because it allows you to look at a snippet and quickly identify out all of the member variables from locals.

You can also achieve this by forcing users to prepend instance variables with "this" but I find this slighly draconian. In many ways it violates DRY because it's an instance variable, why qualify it twice.

My own personal style is to use m_ instead of _. The reason being that there are also global and static variables. The advantage to m_/_ is it distinguishes a variables scope. So you can't reuse _ for global or static and instead I choose g_ and s_ respectively.