Using the 'this' keyword.

H

Harry Colquhoun

For my current job I've encountered a java coding 'technique' in the
existing code that has me scratching my head. Most places in the code
where a method variable is referenced, the previous programmers prefix
the variable with the "this" keyword (i.e. this.myVariable = 10).
Even worse (imho), they've defined their setter methods as follows:

setVariableName(String variableName) {
this.variableName = variableName;
}

Is this a common coding technique that I just haven't seen before? To
me, proper coding style would dictate that you never define a parent
and child class to each have their own variable with the same name,
and therefore use of the 'this' keyword is both dangerous and
unnecessary.

I'm wondering what others think...

Cheers,
Harry
 
J

Joona I Palaste

Harry Colquhoun said:
For my current job I've encountered a java coding 'technique' in the
existing code that has me scratching my head. Most places in the code
where a method variable is referenced, the previous programmers prefix
the variable with the "this" keyword (i.e. this.myVariable = 10).
Even worse (imho), they've defined their setter methods as follows:
setVariableName(String variableName) {
this.variableName = variableName;
}
Is this a common coding technique that I just haven't seen before?

Yes, this is very common in setter methods.
To
me, proper coding style would dictate that you never define a parent
and child class to each have their own variable with the same name,
and therefore use of the 'this' keyword is both dangerous and
unnecessary.

You don't have a parent and child class in the above. You have only
one class, but two scopes: class scope and method scope.
 
P

Paul Lutus

Harry said:
For my current job I've encountered a java coding 'technique' in the
existing code that has me scratching my head. Most places in the code
where a method variable is referenced, the previous programmers prefix
the variable with the "this" keyword (i.e. this.myVariable = 10).

There's no point to that if there is no doubt about what the name refers to.
Even worse (imho), they've defined their setter methods as follows:

setVariableName(String variableName) {
this.variableName = variableName;
}

Is this a common coding technique that I just haven't seen before?

It is commonly seen. Some people prefer this to renaming the local variable.
To
me, proper coding style would dictate that you never define a parent
and child class to each have their own variable with the same name,
and therefore use of the 'this' keyword is both dangerous and
unnecessary.

Yes, but sometimes it happens, and this is how you deal with it.
 
P

P.Hill

Harry said:
I'm wondering what others think...

I asked the same question on this list last year (?)
after wandering away from Java for awhile and
coming back from a language which required the "this" keyword in order
to reference members.

In setters: It looks fine, but can lead to spelling
bugs of the form:

setFooBar( int fubar ) {
this.fooBar = fooBar;
}

Fancy lint programs and IDEs like Eclipse will warn you about this one,
but otherwise you might not notice. Of course, your code wouldn't
get for with this mistake, so I'm not one to worry about it.

In equals methods many people find it very useful to say:

if ( this.field1.equals( that.field1 ) && ... )

There are some similar inner class idioms where "this"
is expected; otherwise most experienced Java
folks find it distracting to see "this" all the
time.

By the way, it does not matter if "variableName" (your example
member) is defined in the current class or some superclass as
long as it is accessable, this.variableName will find it and
reference it correctly.

HTH,
-Paul
 
B

Bryce

For my current job I've encountered a java coding 'technique' in the
existing code that has me scratching my head. Most places in the code
where a method variable is referenced, the previous programmers prefix
the variable with the "this" keyword (i.e. this.myVariable = 10).
Even worse (imho), they've defined their setter methods as follows:

setVariableName(String variableName) {
this.variableName = variableName;
}

Is this a common coding technique that I just haven't seen before? To
me, proper coding style would dictate that you never define a parent
and child class to each have their own variable with the same name,
and therefore use of the 'this' keyword is both dangerous and
unnecessary.

I agree somewhat. For instance, suppose you had this:
class SomeClass {
String variableName;

setVariableName(String varaibleName) {
this.variableName = variableName;
}
}

Note the misspelling in the method. Now, I should note that most IDE's
have a function that generates getters and setters, but trying to
debug the above handwritten code can be difficult.

Just my 2 cents.
 
F

fg

I'm wondering what others think...
Personnaly (and i got this technique from an entreprise I worked for), I
use special prefixes :
for example :
public class MyClass
{
String mObjectName = null;

public void setName(String pName)
{
mObjectName = pName;
}

private void complexMethod()
{
//Some code
String lField = getSomeResult();
useThisString(lField);
//etc
}
}

As a conclusion :
prefix "p" for *p*arameters
prefix "l" (L lowercase) for *l*ocal fields
prefix "m" for global fields (I don't know why "m", they used it, so I used
to code the same way....)



The honnor is mine.

Frédéric.
 
W

Woebegone

prefix "m" for global fields (I don't know why "m", they used it, so I used
to code the same way....)

m for *m*ember. At object scope though, not global.
 
J

Jacob

Harry said:
For my current job I've encountered a java coding 'technique' in the
existing code that has me scratching my head. Most places in the code
where a method variable is referenced, the previous programmers prefix
the variable with the "this" keyword

Identifying class variables are important as they
they have more significance than method variables
and parameters.

I'd find the "this." prefix strange though, as it
somewhat violates data encapsulation; It makes an
object aware of itself _among others_ (I am special,
I am "this"). This is meta-information that only the
programmer or higher level objects should be aware of.

A common technique is to identify class variables
by underscore suffix. See for instance
http://geosoft.no/development/javastyle.html
rule #8. Be careful with variable name _prefixes_
(such as "m" or "_" etc.) as they tend to reduce
the readability of the name.

A side effect of the name suffix is that it nicely
resolves the problem of finding good variable
names for setter methods:

void setName (String name)
{
name_ = name;
}
 
J

Jonck van der Kogel

For my current job I've encountered a java coding 'technique' in the
existing code that has me scratching my head. Most places in the code
where a method variable is referenced, the previous programmers prefix
the variable with the "this" keyword (i.e. this.myVariable = 10).
Even worse (imho), they've defined their setter methods as follows:

setVariableName(String variableName) {
this.variableName = variableName;
}

When you use the automatic getter/setter generation feature in Eclipse
it also uses this structure, perhaps the programmer before you used
this feature to create the getters/setters.
 
M

Michael Saunby

[snip]
I agree somewhat. For instance, suppose you had this:
class SomeClass {
String variableName;

setVariableName(String varaibleName) {
this.variableName = variableName;
}
}

Note the misspelling in the method. Now, I should note that most IDE's
have a function that generates getters and setters, but trying to
debug the above handwritten code can be difficult.

Just my 2 cents.

Indeed when any compiler fails to warn of unused variable mistakes of this
type soon creep in. Which prompt me to ask if anyone knows of a Java
compiler that does generate such warnings? Heck I'd be prepared to consider
unused local variables a complilation error, but I expect the language
definition is quite so totalitarian.

Fortunately I use NetRexx to generate Java code most of the time so the
setter problem isn't such a big deal. See
http://www-306.ibm.com/software/awdtools/netrexx/language/nrsexp.html

e.g. this NetRexx source

class SomeClass
properties indirect
variableName=String

Produced this Java -

/* Generated from 'SomeClass.nrx' 28 Aug 2004 12:28:46 [v2.02] */
/* Options: Crossref Decimal Format Java Logo Trace2 Verbose3 */

public class SomeClass{
private static final java.lang.String $0="SomeClass.nrx";
/* properties indirect */
private java.lang.String variableName;

public java.lang.String getVariableName(){return variableName;}

public void setVariableName(java.lang.String $1){variableName=$1;return;}

public SomeClass(){return;}
}


Michael Saunby
 
P

Paul Lutus

Michael said:
[snip]
I agree somewhat. For instance, suppose you had this:
class SomeClass {
String variableName;

setVariableName(String varaibleName) {
this.variableName = variableName;
}
}

Note the misspelling in the method. Now, I should note that most IDE's
have a function that generates getters and setters, but trying to
debug the above handwritten code can be difficult.

Just my 2 cents.

Indeed when any compiler fails to warn of unused variable mistakes of this
type soon creep in. Which prompt me to ask if anyone knows of a Java
compiler that does generate such warnings?

Supposedly the new 1.5 compiler has a "lint" equivalent command-line option
(-Xlint) that will provide a rather strict evaluation of your source code.
I haven't used it yet (I have slow-dial-up, downloads here are
interminable).
 
J

Jim Sculley

Michael said:
[snip]

I agree somewhat. For instance, suppose you had this:
class SomeClass {
String variableName;

setVariableName(String varaibleName) {
this.variableName = variableName;
}
}

Note the misspelling in the method. Now, I should note that most IDE's
have a function that generates getters and setters, but trying to
debug the above handwritten code can be difficult.

Just my 2 cents.


Indeed when any compiler fails to warn of unused variable mistakes of this
type soon creep in. Which prompt me to ask if anyone knows of a Java
compiler that does generate such warnings?

Eclipse will warn you of such things. In the method above, the warning
would be "The parameter 'varaibleName' is never read".
Heck I'd be prepared to consider
unused local variables a complilation error, but I expect the language
definition is quite so totalitarian.

Eclispe allows you to configure it as an error if you wish as well. It
can also flag a variety of other semantic erros such as unecessary
casts, overridden but not package visible methods, methods with
constructor names, non-static access to static members, assignments that
have no effect, possible inadvertent boolean assignment, empty
statements, empty blocks without comments, and many more.

Jim S.
 
P

Peter Davis

Is this a common coding technique that I just haven't seen before? To
me, proper coding style would dictate that you never define a parent
and child class to each have their own variable with the same name,
and therefore use of the 'this' keyword is both dangerous and
unnecessary.

If you get in the habit of *always* using "this" for *all* instance
variable access, personally I think it's safer. Just the other day I
had to debug some code someone else wrote and discovered this:

private String foo;
public void setFoo(String foo) {
foo = foo;
}

Now that's pretty a pretty dumb mistake to make but it can happen, if
you're not in the habit of always being explicit about which scope
you're talking about.

If you use inner classes, it's also important to be concious of things
like this:

class Outer {
String foo;
class Inner {
String foo;
public void setFoo(String foo, String bar) {
Outer.this.foo = foo;
Inner.this.foo = bar;
}
}
}
 
T

Tony Morris

I fail code during reviews if it uses that horrible naming convention.
Most development environments distinguish between locals and fields as it
is - no need for underscores or m_ or any (C++) oddity like that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top