Using underscores in Java variables and method names [closed]
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
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?
For those using Kotlin, Kotlin recommends using _ for a private property, «If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation detail, use an underscore as the prefix for the name of the private property.» Source: (kotlinlang.org/docs/…)
15 Answers 15
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.
We do use coding conventions without using underscores. Anyway, looking at frameworks and older code, I often saw underscores. The question that consistency rules over convention is clearly to be answerd for consistency but not the point I thought of while asking the question.
Continuing use of ‘_’ character would be a bad practice. This way of working introduce extra maintenance cost and you would have to inform these exceptional conventions to each new developer who is joining the team.
this is like naming interfaces this way: ReadableInterface — absolutely redundant. In modern IDEs you don’t need to specify type of variable or its range — colouring and quick jumping does all the work for you. So IMO this is a bad style as you type redundant characters and force people to read it / maintain it.
sunDoesNotRecommendUnderscoresBecauseJavaVariableAndFunctionNamesTendToBeLongEnoughAsItIs(); as_others_have_said_consistency_is_the_important_thing_here_so_chose_whatever_you_think_is_more_readable();
The question that consistency rules over convention is clearly to be answered for consistency but not the point I thought of while asking the question. Anyway, there are times you should leave old traces, eh?
If a «conflicting» naming convention is already in use, I think it depends on how much code we are talking about. I wouldn’t recommend rewriting thousands of lines of code just to go from old_convention to newConvention, given that the old convention is used consistently.
LOL! That being said, when code gets pasted in editors that have spellcheck, then the ‘misspelled’ words are underlined, thereby obscuring the underscore. This is a good reason to not use underscores. Also, Camel case is shorter. Finally, the shift key is easier to use on letters than on the upper row (i.e shift dash ‘-‘).
@Tihamer Others would argue that the snake_case form is easier to read. Especially with short words (1-2 letters), I would definitely argue that this is the case. As for «hard to type», typing a word with lotsOfMixedCaseWithinIt is not precisely convenient either. I’d advocate that it’s a matter of what you are used to. In Java though, I say «use the common form» as recommended by the JLS/etc. In Ruby/Python/C, use snake case. And so on.
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.
This question was about asking about Java underscores in general, not about asking them only at member variables (though this was an example in the question).
Writing this.foo (or this->foo in C++) would probably be a much clearer way of differentiating locals and fields / member variables.
«Bad style» is very subjective. If a certain conventions works for you and your team, I think that will qualify a bad/good style.
To answer your question: I use a leading underscore to mark private variables. I find it clear and I can scan through code fast and find out what’s going on.
(I almost never use «this» though, except to prevent a name clash.)
Like you said, style is very subjective. I tend to use this quite liberally to indicate a member variable if I think that it needs attention drawn to it. However, I’m not a zealot about it.
Using ‘m_’ or ‘_’ in the front of a variable makes it easier to spot member variables in methods throughout an object.
As a side benefit, typing ‘m_’ or ‘_’ will make intellsense pop them up first 😉
If you’re programming Java, most likely you will have an IDE that will colour your member variables in a different colour. «m_» is just nasty.
There is a reason why using underscores was considered being bad style in the old days. When a runtime compiler was something unaffordable and monitors came with astonishing 320×240 pixel resolution it was often not easy to differentiate between _name and __name .
Here’s a link to Sun’s recommendations for Java. Not that you have to use these or even that their library code follows all of them, but it’s a good start if you’re going from scratch. Tool like Eclipse have built in formatters and cleanup tools that can help you conform to these conventions (or others that you define).
For me, ‘_’ are too hard to type 🙂
- I happen to like leading underscores for (private) instance variables. It seems easier to read and distinguish. Of course, this thing can get you into trouble with edge cases (e.g., public instance variables (not common, I know) — either way you name them, you’re arguably breaking your naming convention:
private int _my_int; public int myInt;? _my_int? )
Ultimately, you’re going against the rest of the (Java) world’s preferences and are likely to have some annoyances from that. And as previous posters have mentioned, consistency in the codebase trumps all of the above issues.
Setting up Eclipse to understand your prefix (or suffix) preferences is pretty straight-forward. In Preferences->Java->Code Style there’s a table where you can set the variable name conventions for fields, static fields, static final fields, parameters and local variables. All the code generators appear to respect these settings.
It’s nice to have something to distinguish private vs. public variables, but I don’t like ‘_’ in general coding. If I can help it in new code, I avoid their use.
It’s a blend of coding styles. One school of thought is to preface private members with an underscore to distinguish them.
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.
That’s fair enough, but then aBar shows up in the method signature in the API, and I think it looks messy.
I actually ran into a case where autogenerated code matched one of the language keywords, so the best way to avoid this was to prepend a _ at the beginning.
I think any style that breaks a language’s own style guidelines (without due reason) is ugly and therefore «bad».
No doubt the code you’ve seen was written by someone who used to work on a language where underscores were acceptable.
Some people just cannot adapt to new coding styles.
I mostly agree with the «do as others do» philosophy when coding, but not as an absolute. I think there is a very strong argument that, given reasonable identifier lengths, that snake_cased_variables are easier to read than CamelCasedVariables. My justification is that reducing cognitive load visually is a small thing, but still useful. People appreciate white space in code, when reading documents, and listening to music. Camel case, I think, is an affront to white space in the name of ‘efficiency’. Efficiency for who?
The reason people do it (in my experience) is to differentiate between member variables and function parameters. In Java you can have a class like this:
If you made the member variable _var1 or m_var1, you wouldn’t have the ambiguity in the function.
So it’s a style, and I wouldn’t call it bad.
Personally, I think a language shouldn’t make rules about coding style. It is a matter of preferences, usage, convenience, and concept about readability. Now, a project must set coding rules, for consistency across listings. You might not agree with these rules, but you should stick to them if you want to contribute (or work in a team).
At least, IDEs like Eclipse are agnostic, allowing to set rules like variable prefixes or suffixes, various styles of brace placement and space management, etc. So you can use it to reformat code along your guidelines.
Note: I am among those keeping their old habits from C/C++, coding Java with m_ prefixes for member variables (and s_ for static ones), prefixing Booleans with an initial b, using an initial uppercase letter for function names and aligning braces. The horror for Java fundamentalists! 😉
Funnily, that’s the conventions used where I work. probably because the main initial developer comes from the MFC world! 😀
Java constant variable, naming convention [duplicate]
Is there any naming convention for java constant variable?
Normally we use variables with names containing uppercase letters and underscores( _ ).
For example:
public final class DeclareConstant
5 Answers 5
Yes. That is it. It is often used for enum as well.
The only common exception is for logging where you might see
private static final Logger log = Logger.getLogger(getClass().getName());
I often write this as UPPER_CASE, but I also write TitleCase for classes and camelCase for variables and methods.
Why in case of Logger we use private static final Logger log = Logger.getLogger(getClass().getName()); ?
Im not sure that’s true @peter-lawrey. Things File.separator in the API are lower case. I thought the convention was that if the rhs has to do something eg get a logger then it is lower case. If it is truly a constant then it is upper case
That is right. According to Sun:
Constants
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.)
static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;
There doesn’t seem to exist any Java-related definition for ANSI constants. (sources: SO, coderanch.com)
@chepner — Nice comment! As of now, the link is dead, I was able to read the relevant part thanks to you 😉
How about when It comes to groups. Something like : ACTIVE_STATUS_ACTIVE, ACTIVE_STATUS_INACTIVE. I have seen some people use two Underscores to divide group name. Like this: ACTIVE_STATUS__ACTIVE, ACTIVE_STATUS__INACTIVE. Is this a standard to use?
Many of these naming conventions were created well before IDEs were in widespread use. These days, static constants are going to be colored differently than local variables, so the need to use a specific naming convention to identify them is greatly reduced. I would suggest that readability is a more important concern these days, and recommend using camel case instead.
To answer your question though, the other answers are right that this is the official convention. 😉
Readability is enhanced by upper-case constants I would say. Even though modern IDE’s help too of course. Some notations say you should have an «m» before member-variables, e.g. mMember as well, however, in that case where the name is actually altered I would say using IDE-coloring is enough these days.