MaheshVarma
MaheshVarma

Reputation: 2125

Use of underscore in variable and method names

I got confused with the (naming convention) use of underscore _ in variable names and method names as their starting letter. For example, _sampleVariable and _getUserContext(). When should I use it?

Upvotes: 16

Views: 39605

Answers (5)

E_K
E_K

Reputation: 2249

Quoting the book Clean Code by Robert C. Martin,

Sometimes it is useful to warn other programmers about certain consequences.

Example

// Don't run unless you
// have some time to kill.
public void _testWithReallyBigFile() {
    writeLinesToFile(10000000);
    response.setBody(testFile);
    response.readyToSend(this);
    String responseString = output.toString();
    assertSubString("Content-Length: 1000000000", responseString);
    assertTrue(bytesSent > 1000000000);
}

Nowadays, of course, we’d turn off the test case by using the @Ignore attribute with an appropriate explanatory string. @Ignore("Takes too long to run"). But back in the days before JUnit 4, putting an underscore in front of the method name was a common convention.

Upvotes: 7

Pavan Kumar K
Pavan Kumar K

Reputation: 1376

Usually _ is used in variables to represent them as class level private variables.

Upvotes: 3

Leep
Leep

Reputation: 457

Sometimes people use underscores to indicate that their variable or method is private. I do not like this way of doing it. I suggest you to use lower camel case too.

Upvotes: 10

Audrius Meškauskas
Audrius Meškauskas

Reputation: 21748

Normally it should not be used, except as a separator in all uppercase constants that are usually final (allStars but ALL_STARS).

Exactly because normally not expected, the underscore is abundant in generated code. It may also be found in some older code, but this is not the reason to continue using it.

Upvotes: 3

user1907906
user1907906

Reputation:

See the Java Naming Conventions

Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)

Upvotes: 16

Related Questions