As kind of a follow up to this question about prefixes, I agree with most people on the thread that prefixes are bad. But what about if you are using getters and setters? Then you need to differeniate the publicly accessible getter name from the privately stored variable. I normally just use an underscore, but is there a better way?
views:
409answers:
6In a case sensitive language I just use:
private int myValue;
public int MyValue
{
get { return myValue; }
}
Otherwise I would use an underscore
Private _myValue As Integer
Public ReadOnly Property MyValue As Integer
Get
Return _myValue
End Get
End Property
There are almost as many different ways of doing this as there are programmers doing this, but some of the more popular ways include (for a property Foo
):
- mFoo
- m_foo
- _foo
- foo
In java there is this.foo in python there is self.foo and other languages have similar things, so I don't see a need for naming something in a special way, when I can already use a language construct. In the same context good IDEs and editors understand member variables and give them a special highlight, so you can really see it w/o using special names.
This is a completely subjective question. There is no "better" way.
One way is:
private int _x;
public get x():int { return _x; }
public set x(int val):void { _x = val; }
Another is:
private int x;
public get X():int { return x; }
public set X(int val):void { x = val; }
Neither is the right answer. Each has style advantages and disadvantages. Pick the one you like best and apply it consistently.
I like prefixing fields with an underscore, as others have mentioned.
private int _x;
I think this goes beyond straight personal preference though (as David Arno said in this thread). I think there's some real objective reasons for doing this:
- It means you avoid having to write "this.x = x" for assignments (especially in setters and constructors).
- It distinguishes your fields from your local variables/arguments. It's important to do this: fields are trickier to handle than locals, as their scope is wider / lifetime is longer. Adding in the extra character is a bit of a mental warning sign for coders.
- In some IDEs, the underscore will cause the auto-complete to sort the fields to the top of the suggestion list. This makes it easier to see all the fields for the class in one block. This in turn can be helpful; on big classes, you may not be able to see the fields (usually defined at the top of the class) on the same screen as the code you're working on. Sorting them to the top gives a handy reference.
(These conventions are for Java, but similar ones exist for other languages)
These things seems small but their prevalence definitely makes my life easier when I'm coding.
I like writing "this.x = x". It's very clear to me. Plus, when using Eclipse, you can have it automatically generate your getters/setters this way.