Before forming a class in Java or other programming languages that support OOP, should I use underscore (_) in each (local or private) field declaration.
More precisely:
private String _customername;
Is this a correct declaration?
3
There is a strong convention in java circles of not using _
for member names (as opposed to C++ circles, where there is a strong convention for using them). This is largely an arbitrary difference that probably has more to do with the desire to reinforce a sense of community than with measurable advantages. It is usually a good idea to go along with a convention simply because it removes one barrier for other people to understand your code quickly.
However, the necessity of marking member variables at all is questionable. In my view, if your methods are so long that a reader has trouble telling local vars from member vars, then they are too long to begin with, and you should refactor them to be smaller and more self-contained rather than disambiguate via naming conventions.
1
I think this is a matter of personal preference. I use underscores on private fields because I feel it makes it easier to read and identify the scope of the fields quickly. As far as I am aware, there are no rules defining which style you should use.
Note: I develop in C# primarily.
6
In languages with language-level properties (haxe, actionscript, ..) an underscore is sometimes used when naming a private variable that is also accessible using a property. The point here is avoiding a name collision between the property and the private value.
private var _width:Number;
public function get width():Number
{
return _width;
}