Alex Rivera | Logout

Using underscores in Java variables and method names

Asked 2008-09-29T19:15:06.653
92

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?

Edit
Report

3 Answers

37

Rules:

  1. Do what the code you are editing does
  2. If #1 doesn't apply, use camelCase, no underscores
answered 2008-09-29T19:19:46.547
33

I don't think using _ or m_ to indicate member variables is bad in Java or any other language. In 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 slightly 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 variable's scope. So you can't reuse _ for global or static and instead I choose g_ and s_ respectively.

answered 2008-09-29T23:05:35.913
4

It's a blend of coding styles. One school of thought is to preface private members with an underscore to distinguish them.

setBar( int bar)
{
   _bar = bar;
}

instead of

setBar( int bar)
{
   this.bar = bar;
}

Others will use underscores to indicate a temporary local variable that will go out of scope at the end of the method call. (I find this pretty useless - a good method shouldn't be that long, and the declaration is right there! So I know it goes out of scope.) God forbid a programmer from this school and a programmer from the memberData school collaborate! It would be hell.

Sometimes, generated code will preface variables with _ or __. The idea being that no human would ever do this, so it's safe.

answered 2008-09-29T19:20:35.780

Your Answer