views:

501

answers:

16

Possible Duplicate:
Do you prefix your instance variable with 'this' in java ?

Coding standards question. Maybe should be Wiki, let me know. Should I qualify all my instance properties and methods with this. or should I leave it off. Do you think it makes statements more readable and traceable? Or is it just a few wasted keystrokes?

+2  A: 

Personally, I don't like to have a "this."

Josh
+1  A: 

I'm not sure there is a definitive answer one way or the other. In my opinion it does help readability, but I can see where people might think it clutters up the page.

Matthew Jones
When it "clutters up the page" it is hurting readability. :(
dss539
A: 

I mainly use "this" to help point out the difference between instance and static members. But if I don't have a mix I would normally avoid the "this"

Matthew Whited
+7  A: 

Leave it off, it doesn't bring any value. Even ReSharper suggests you should remove it because it is redundant.

Otávio Décio
Redundancy is nothing compared to clarity and security. Resharper is wrong here imho.
annakata
Also "no value" is clearly subjective.
annakata
@annakata - clarity? If you can't figure out if the variable you are looking at is defined in the function, your function is too big - not clear or secure. If you can't find it in the current class, it comes from a parent class, which is not clear or secure.
Otávio Décio
@ocdecio - what you're missing is how future readers will read and understand it. *You* should damn well know, but the guy a year later maybe not. Parent classes is kind neither here nor there.
annakata
@annakata, and remember "the guy a year from now" is almost certainly going to be your own self. Clarity now = a little less pain in your own future....
Bob Cross
+2  A: 

The advantage is that it can prevent silly mistakes like this:

private String value;


public void setValue(String value) {
    value = value;
}

But I would still be inclined to not require it. Especially if you are using an IDE that color codes the difference.

A nice convention if you want to prevent the mistake with a standard of always using this is Hungarian notation where fields are prefaced with an f, so the example becomes:

private String fValue;

public void setValue(String value) {
    fValue = value;
}

You see that convention in the JUnit source code, for example.

Yishai
some compilers will catch this (eclipse for example)
Scott Stanchfield
egad, hungarian over this?
annakata
You can't forget hungarian once you do it in the field definition. this can be left out at any time.
Yishai
Marking your parameters final would also prevent this.
Michael Myers
public string Value{private get; public set;} is way better than what you have there.
dss539
@dss539, this was a java and c# question. Java has no such convension.
Yishai
@mmyers, for me final would imply it is actually used in an inner class, but it is certainly a legitimate alternative as a coding convension.
Yishai
+10  A: 

Using a good naming convention obviates the need for using "this" for readability.

Gerald
I hate when people this.ingThe only thing ugliest is "class Foo extends Object"
alamar
@Gerald, what naming convention (that I would have to explain to each new employee and enforce across the team) would be more useful than the syntax that's built into the language? That's a serious question; I'm not just being snarky.
Bob Cross
@Bob, most naming conventions would do. Anybody who is a programmer should know that mValue is a member variable, for instance, even if it's not their preferred naming convention. The idea is that it's better to tie the naming convention tot he class definitions, where they are guaranteed to be consistent across all usages of that variable. The language construct is not required, so a variable of "value" could be "this.value" or just "value" in various places. When you tie the convention to your definitions, the compiler enforces the consistency of its usage.
Gerald
Imagine being a code reviewer who has to check every line of code to see if "this." is being used, instead of just checking the interfaces?
Gerald
mValue, underscores and the like are all terrible for anyone who actually reads the code (I hear "muh-Value" in my head when I see that). They are also unenforceable: are you going to force the developers to prefix all of their member variables with an "M"? Why do that when the language already provides "this" for times when you need clarity?With respect to code review: I use PMD, FindBugs and the compiler. Each one of those can detect a mis-assignment in a different and useful way. I certainly wouldn't want to have to write an "mValue" detector for PMD.
Bob Cross
"They are also unenforceable: are you going to force the developers to prefix all of their member variables with an "M"?" Yes, that's kindof why it's called a coding standard. And it's definitely enforceable. "Why do that when the language already provides "this" for times when you need clarity?" -- because if you have a good naming convention, you don't have to decide when the "times when you need clarity" are. The naming convention is universal. And they're useful for more than just deciding if a variable is a member variable or not, so you still need a convention even if you use "this."
Gerald
We've been using the same naming convention standard for 15 years, and we never have any problems with new employees understanding it, or any problems enforcing it. If you have problems enforcing your standards, you have much deeper problems.
Gerald
Sorry - I find superfluous prefixes to be less than helpful which is why I changed our coding standard to remove them. The decrease in readability combined with the breaking of the standard bean pattern where two of the reasons. As I said in my answer, I strongly favor using "this." where it's appropriate (i.e., when it increases clarity) and not when it's not.
Bob Cross
Well obviously it's a matter of taste. Most people I know find that the "superfluous" prefixes helps readability. And your last sentences points to the reason for that. Having to even think about increasing clarity on a case-by-case basis speaks to lost productivity. With a good naming convention, you don't have to think about it, because with a standard naming convention, the clarity is built in. I can understand your point about the "standard bean pattern", though. Since we're primarily concerned with C++ and C#, that's not an issue for us. If we were a Java shop, it might be different.
Gerald
+11  A: 

I use this when I think it will communicate more clearly without cramping my style. In particular, set methods are a great place where I like to have the clear match between the data member and the method parameter:

public void setImportantValue(double importantValue) {
    this.importantValue = importantValue;
}

With colorized IDEs, this is a little bit redundant but if it helps me work better with my fellow humans, it's a win.

Edit: Thorbjørn reminded me of an excellent point:

Using "this" allow you to have the same name for the parameter as for the field, which clearly shows intent. Also the parameter name ends up in the signature which is what you see in the IDE - having correspondence between setter name and argument removes all doubt.

I was reminded that the user of your code usually only sees your external API. For example, if we want to make it clear to the user (either via javadoc, code completion or IDE mouse-overs) that a method is going to adjust the Euler angles of a simulated airplane, we might use a method such as:

public void setOrientation(double roll, double pitch, double yaw) {
    this.roll = roll;
    this.pitch = pitch;
    this.yaw = yaw;
}

It is clear from the externally-exposed interface and the parameter names what I'm trying to accomplish. I could even make things a little more clear with @param javadoc tags.

The fact that I need to do a little more typing of "this.roll", etc., is a very small price for me to pay to make the both API-user's life easier and the API-maintainer's task more clear. This is especially true since I only pay the price once.

Bob Cross
Fail @ naming.
dss539
This is one of my favorite uses of this.
instanceofTom
@dss539, you don't like my example or you don't like my answer?
Bob Cross
+1 for the setter snippet. Using "this" allow you to have the same name for the parameter as for the field, which clearly shows intent. Also the parameter name ends up in the signature which is what you see in the IDE - having correspondence between setter name and argument removes all doubt.
Thorbjørn Ravn Andersen
@Thorbjørn, Good point - I'll put that in the answer. Thanks.
Bob Cross
+3  A: 

I always use it - I find it helps me think more about what I'm doing, and if something should be scoped to the class.

I didn't use it before I started running StyleCop on everything - now I've converted.

Joe
How does putting "this" in front of a method invocation help you?
Steve Kuo
+3  A: 

It does bring a provide distinction between local and instance variables, for one. this can easily replace prefixes some people like to use for that purpose. For me, though, I like to use for IDE autocompletion- it's a bit lazy, but oh well.

itrekkie
+1 for laziness, even though I usually avoid 'this'
dss539
A: 

I say "only if necessary" as in

public void setFoo(Foo foo) {
    this.foo = foo;
}

The big disadvantage to using it other places is that if you want to change between instance/static/local you have more work to do. (I just had to do this to some code and it wasn't fun...)

Scott Stanchfield
Fail @ naming.
dss539
A: 

I limit the use of the keyword this in my code to only those situations that it is necessary to achieve the correct behavior.I would avoid using it whenever it is already understood.

Examples of where 'this' is required to achieve desired behavior include constructors and often in equals(Object o) method implementations.

Brian
+1  A: 

IMHO the clarity is always worth a few extra characters, and is a far stronger defence than relying on an ephemeral naming convention.

Saving on typing has always been a weak excuse.

annakata
So don't use an "ephemeral" naming convention. Pick one and stick to it. Better to use a convention that can be enforced by the compiler than one that may be used intermittently.
Gerald
How is that a defence of naming conventions? this. is happily enforceable by the compiler, naming conventions vary from coder to coder.
annakata
Naming conventions will only vary in the definition, and are *always* enforced by the compiler elsewhere. You can never use "value" to reference "mValue" somewhere else in your code, but you can use "this.value" or "value" to reference the same thing in different places.
Gerald
+1  A: 

Using this for clarity in general is not really useful, since if you have to make it explicit to distinguish it from others, you probably should clear up your method a lot, maybe dividing it into sub methods. An exception is the setter method pattern, so that you don't have to invent arbitrary prefix for the instance variable.

When code contains additional elements that doesn't bring anything useful, the meaning of program gets cluttered. If you prefer using this, why not also qualify every object instead of importing it?

egaga
+1 for refactoring suggestion. If you have to use 'this.' to make it clear, there's probably a bigger problem.
dss539
+2  A: 

matter of taste I think. a proper naming convention generally makes use of "this" unnecessary.

Perpetualcoder
+1  A: 

I really don't understand why people put this in front of method invocations.

this.someMethod();

someMethod() could be in this class, the parent's class, or static. In this case this doesn't add any value or information. So I'd say in the case of methods, don't use this.

Steve Kuo
A: 

I always prefix instance variables with 'this'.

  1. It makes the code more robust in the face of refactoring. For example, if an instance variable is being used in a method and I add a local variable or method parameter with the same name without realising my mistake, then I have introduced a bug without any warning from the compiler.

  2. It makes it more obvious which variables are instance variables. Generally speaking, the more instance variables you have the more vulnerable your code is to multi-threading issues. I'm not saying you should avoid instance variables, because there are cases when they make your code cleaner, but its nice to be able to see at a glance where they are. The 'this' qualifier is the best way of achieving this.

  3. It allows the IDE to provide code completion, thereby resulting in LESS typing, not more.

  4. Code is not always viewed in an editor that has syntax highlighting. e.g. some diff tools.

Kevin Stembridge