The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

Derefencing using "this" the WHOLE time.

(apologies if this gets a bit long)

Has anybody any experience of a coding style that insists you use "this" (or its equivalent in your language of choice) for EVERY reference to an object's own data/fields?

For example:

public class MyClass {
  private int anInt;
  private String aString;

  MyClass (int anInt, String aString) {
    this.anInt = anInt; // disambiguation; that's OK
    this.aString = aString; // and again
  }

  public int getInt () {
    return this.anInt; // why "this." ???
  }

  public int getString () {
    return this.aString; // again, why "this." ???
  }

  public int pointlessCalculation () {
    return this.aString.length() + this.anInt; // why????

    // Why not just:
    // return aString.getLength + anInt;
  }
}
 
I've just joined a new company and although I'm supposed to be a C++ programmer, I seem to have been swapped into Java development, which I've not touched since I took a course 6 years ago; I assumed it was just a recent coding idiom that I'd not come across before but I can't find any references anywhere via google.

I've never encountered it in 10+ years of C++ development, but I noticed a colleage doing it in new C# code yesterday as well.

Explanations I've had from my new colleagues are:

"Absolute best practice" (says who?)
"Josh Bloch recommends it in Effective Java" (not that I can see; he only uses it for disambiguation)
"It forces you to change all your references if you change a field to being a local variable" (a. why is this a good thing? b. how often do you do that anyway? I usually find I'm going the other way; promoting local variables to class level)
"It ensures there are no problems if someone creates a local variable with the same name" (OK, I appreciate this; but given there is a proscription in the local coding standard against knowingly "hiding" variables in an outer scope anyway, this shouldn't be happening if people are paying attention)

So, can anyone find me a reference to a recognised authority that says you should do this? Or is this, as I suspect, an "emperor's new clothes" situation and actually this "absolute best practice" is absolute twaddle that's accepted by new hires (until now ;-])for an easy life?

Cheers,

Rob
p.s. Someone's also mentioned that all references to statics defined for the same class have to be fully qualified as well. Aaargh!
Rob G Send private email
Tuesday, February 14, 2006
 
 
Oops, please no-one point out that one reason for not using "return aString.getLength + anInt;" would be that aString.getLength isn't correct. I changed the first one, missed the second:-(

I tell you (well, imply, anyway) that my Java was rusty!
Rob G Send private email
Tuesday, February 14, 2006
 
 
Oh, that's just gross!

I have heard arguments for always using access methods but always using this seems strange and verbose with no upside.
Chris Nelson Send private email
Tuesday, February 14, 2006
 
 
it's just stupid horribleness.

making local vars with same name as instance ones should be punished by code that breaks anyhow, it's so dumb.

in oo perl you are forced to always do this, and it is one thing I don't much like. Apparently it will change in perl 6 though.
revert my buffer
Tuesday, February 14, 2006
 
 
Some languages force you to do this, but speaking about Java and C#, I can say people use this technique because typing "this." will generally determine the IDE to show you all the fields and methods of the current instance, which can be very handy, while simply tapping CTRL+Space will display all the visible classes as well (which are generally very many). I totally dislike this style and delete the "this." when I get in contact with such a code. It's also a great pleasure for me to delete unnecessary spaces at the end of the lines...
smalltalk Send private email
Tuesday, February 14, 2006
 
 
I use this. all the time, for just one simple reason :

Code Readability :

when you see 'this.' you know that it applies to a classlevel something (property, method, ...). don't look further, don't think about static methods, or anything like that.

The intellisense thing helps to :)
ssst
Tuesday, February 14, 2006
 
 
I do this, and indeed have a macro shortcut for "this->" in each of the editors I use. I doubt I'd count as any kind of authority, but it does makes it easy to see what's going on.

It is rare that member functions have adorned names, and nobody (except for the original coder) likes adornment on public variables, so it is useful for these two situations if nothing else.
Tom_
Tuesday, February 14, 2006
 
 
I have seen people do it but have never seen such an ugliness recommended by anyone who knew what they were doing.
argon Send private email
Tuesday, February 14, 2006
 
 
I wasn't aware of the issue with perl forcing you to do things this way and I suspect that's where it's come from. Yuk!

As for "readability", I don't think that holds true; certainly not the way I read code. I prefer code to be concise (i.e. short) and adding "m_" or "_" to all fields is enough to indicate that you're using a field, not a local variable. Also, once you've defined the name of a member as "m_age", you're FORCED by the language to use "m_" on every reference, which is not true of the "this." convention which could then cause confusion when someone forgets to use it.

In any case, if there's confusion about what you're doing with the data in a method/calculation/whatever (and where the data are coming from) you should be using COMMENTS, not arcane coding style rules, to make things clearer, surely?

Rob.
Rob G Send private email
Tuesday, February 14, 2006
 
 
perl is not the only one that forces you to do this. python is another example. I suppose it's a necessity in every language that has no variable/field declarations.

in python it comes from more general rule: explicit better than implicit, which is used in many more language aspects.

my personal preference (I work in Java) is never to use it. I'd rather change the name of parameter or local var than use 'this.'.
szeryf
Tuesday, February 14, 2006
 
 
it happens in perl because of the way perl's oo works. You get the instance that the method was called on as the first arg, you typically assign that to a var called $self, then do

$self->anotherMethod()

which causes $self to be the first arg to teh anotherMethod call.

I doubt VERY much that this (very idiosyncratic) oo style has any influence at all on all the eclipse/java heads out there.
revert my buffer
Tuesday, February 14, 2006
 
 
I do it sometimes for the Intellisense thing as well. I don't do it in Java much and I would never make it a standard. In my opinion, it is much better to have a standard naming convention that avoids this problem entirely.

Here are my C# rules. These completely negate the need to preface private members with "this".

1) I name private members of the class starting with an underscore.

    private int _nextIndex;

2) I name method arguments with lower case.

    public void MakeNewFoo(int nextIndex) {}

3) Properties are upper case.

    public int NextIndex
    {
        get { return _nextIndex; }
        set { _nextIndex = value; }
    }


There is no need to dereference everything with "this" if you follow these rules.
Turtle Rustler
Tuesday, February 14, 2006
 
 
"When you see 'this.' you know that it applies to a classlevel something (property, method, ...). don't look further, don't think about static methods, or anything like that."

Hmmm. I would say "instance level" rather than "class level". Class methods and static methods are the same thing.
John Topley Send private email
Tuesday, February 14, 2006
 
 
I think that if using "this" bothers you that much, you've probably got some "issues" of your own that you need to work out.  There's folks out there called psychologists and psychiatrists whose sole purpose is to help you work through your troubles.

I personally couldn't care less wheter there's a this or not.  I do it when I'm feeling lazy and want the code insight to work for me.  I sometimes name my parameters with the same name as my class member; sometimes it just can't be helped.  "This" in the code certainly does not harm readability, and sometimes helps it.
newby
Tuesday, February 14, 2006
 
 
Sun's "Java(TM) Coding Style Guide", http://developers.sun.com/prodtech/cc/products/archive/whitepapers/java-style.pdf, does not explicitly speak to this, but does not use the "this." in its examples.
George Jansen Send private email
Tuesday, February 14, 2006
 
 
You've never encountered the keyword 'this' in 10 years of c++ development!  I'm sure glad you don't work for me.
are u serious ?! Send private email
Tuesday, February 14, 2006
 
 
In some languages you can use a . prefix instead of (this-> or this.) and I find that's fairly elegant.

type somefunction()
{
  .membervar++;
  .memberfunction();
  return
}

Typing this-> at every opportunity seems unnecessary to me. If you're typing this-> you might as well type this->this->this->member. Really, I don't get it. It doesn't avoid confusion (except in a a few particular situations, but the exception doesn't prove the rule). It makes the code longer (thus harder to read), and it makes refactoring harder (which is bad).

But really, this shouldn't even be a problem. Even if a group/team has a coding standard it's remarkably childish to bicker about stuff like this. (I'm not suggesting any bickering has taken place -- hypothetical)

If somebody is used to write this->, and if it helps him keep variables apart, that's great. Other people strongly believe in prefixing members with an underscore or with m_. That's fine with me too. Other people use camelcase/pascalcase to differentiate between the two.

Does it matter? Not an iota.
Curious
Tuesday, February 14, 2006
 
 
Ooohh, boy. Some people have *strange* problems.

I don't think this coding style is yukky or gross or arcane at all. In fact, my code is full of it. In part, because IntelliJ IDEA automatically generated code following this pattern when inserting properties. ALT+INS to insert getters and setters and this is what you get:

private int problems;

public void setProblems(int problems)
{
  this.problems = problems;
}

public int getProblems()
{
  return this.problems;
}

Its been doing this for ages, so it's definitely not a "new phenomenon". Why on earth should you call the parameter to a setter anything else than the variable it sets, esp. if there is a language construct which makes sure your code is unambiguous?

And to argon - I am *very* sure that everybody at IntelliJ definitely falls into the category of "anyone who knew what they were doing."

And I'd be 1000% more prepared to accept a coding and disambiguation rule that relied on clear language concepts rather than on more or less arbitrary variable name prefix conventions.

You could also argue that it makes refactoring easier, since you can move code blocks around and into other methods (or new methods) while keeping it absolutely clear where you're referring to instance variables and where to local variables (although I mainly use IntelliJ's integrated refactoring support which keeps track of this for me and chenges references where necessary).

Although I do agree with the OP that the  pointlessCalculation () method is taking it a bit far.

Dan.
Daniel Send private email
Tuesday, February 14, 2006
 
 
You misunderstand, Mr Serious: of course I've encountered "this" in C++ development (and Java, and "self" in SmallTalk, etc.).

I had never before come across a coding style that uses it continuously for dereferencing the current object when accessing that object's fields and methods.
Rob G Send private email
Tuesday, February 14, 2006
 
 
I always use the "this." style, coupled with the properly scoped static usage too.

+ It gets me thinking in a more object-oriented way.

+ It improves the speed at which I can read AND understand code.

+ My IDE helps me out big time.

+ In .NET IL code always uses the equivalent of "this." so when I use .NET Reflector (disassembler) my code looks more like it does in Visual Studio.  No "this.m_var" for me. :p

+ It allows me to name my member and local variables to anything I want.
Edward James Send private email
Tuesday, February 14, 2006
 
 
IMHO, there's a very good reason to make references to member variables stand out. The values you set to these variables persist even after you exit your function, and *could* cause side effects elsewhere. So the same kind of caution applicable to global variables applies, but at a much less serious level. I personally prefer the "m_" prefix: it is  short enough not to interfere with your reading of the variable, and distinct enough to get help from IDEs, etc.
Martin
Tuesday, February 14, 2006
 
 
I've seen some programmers do this before, mostly not such good ones, but it's a small sample size. I think the reason for it is mainly to enable intellisense.
GROK!
Tuesday, February 14, 2006
 
 
I know people who love doing this in C#. Personally I hate it. I'm with the OP and Turtle Rustler on this one

int _field;
void SomeMethod(int parameter)
string StringProperty { get; }

This is the style used by the core .NET base class library team - if you read the Rotor (SSCLI) source, it's mostly written like this. Funnily enough the latest FXCop rules say that prefixing identifiers with an underscore is a no-no, but unless I have to pass FXCop because I'm doing Windows logo stuff, there's no way you're getting me to stop it.

It also seems to have become a de-facto standard in the C# community - not that there aren't other standards, but this is the one I see most often. Anything to avoid Hungarian - yuk. Now that *is* the spawn of Satan. And I don't care what Joel says <g>.
.NET Guy
Tuesday, February 14, 2006
 
 
I've seen it, and I don't like it. I typically use an m_ prefix (in C++) or a _ prefix in C# and Java.
sloop
Tuesday, February 14, 2006
 
 
I use this (or Me in VB .NET) for the Intellisense.  I find that it's easy enough to scan past.  I could go either way on it, but prefer to use it for convenience.

Now Hungarian, on the other hand, is just plain wrong.  No room for disagreement on that.

Well...unless you're naming UI elements, and then I guess it's OK.

But never any other time.
Kyralessa Send private email
Tuesday, February 14, 2006
 
 
The coding standards at the current client don't allow for the leading underscore, so using this is often necessary in properties where the parameter (set) is spelled the same as the class-level member.  :rolleyes:

But using it every single time is excessive.  Usually I'll use it to make explicit what scope the variable is.
example Send private email
Tuesday, February 14, 2006
 
 
The code for the .NET Framework has no suffix for any member fields I've seen.  The style used throughout is:

 this.field
 this.Method()
 MyClass.StaticMethod();

If it's good enough for the guys/girls who invented the technology, it's good enough for me.
Edward James Send private email
Wednesday, February 15, 2006
 
 
Have you seen the actual source code, or are you talking about Reflector output? Reflector will add "this" to any instance field & method access. IL does not preserve whether or not it was present in the original C# source code.

Personally, I prefix all instance field accesses with "this" but not method calls. There's no way to mistake a method call for something else, unless you like using capitalized names for delegate variables!
Chris Nahr Send private email
Wednesday, February 15, 2006
 
 
No I've not seen the code, so perhaps I should revise my statement.  From Reflector I can see that Microsoft haven't used any prefix notation for their member fields.  I can only assume that they use 'this' keyword to identify the difference between member and local variables.
Edward James Send private email
Wednesday, February 15, 2006
 
 
In Visual Studio 2005 (the only Microsoft IDE I have to check with at the moment, but I believe this works for VS2003 as well) if I hovers my mouse pointer over a member variable then a tooltip is displayed showing its definition, in the form

  int CMyClass::someMemberVar;

Obviously if I hover over a local variable or a parameter, the definition is of the form

  int someLocalVar;

The inclusion or lack of a class name on the declaration makes it quite obvious which is which.

I would be very wary, therefore, of asserting/assuming that the .Net library developers needlessly add "this." to the front of their field references; this feature is the oft-quoted reason why Hungarian notation is now supposedly considered anathema at Microsoft. It's highly unlikely (IMO) that they've taken the approach of "Hungarian notation is no longer necessary, but lets use a coding style involving 'this.' which is equally unnecessary" for the .Net library.
Rob G Send private email
Wednesday, February 15, 2006
 
 
Field names in Reflector are exactly the same as those in the source code (in the case of my current employer, "m_" is the standard and so we get "this.m_var" in Reflector).  When looking at the .NET Framework assemblies I see that the fields don't have any Hungarian notation at all.  I'm just saying what I see.  I assume that the coders used the 'this' keyword to help them differentiate between fields and local variables.  If they didn't then they might have had some trouble, especially with Properties.
Edward James Send private email
Wednesday, February 15, 2006
 
 
I haven't done a detailed analysis, but as an example, if you use Reflector to browse into mscorlib -> System.Collections -> ArrayList, you'll see that the fields in the class are underscore-prefixed (for example, _items for the array of objects that holds the actual list data). Ditto Stack and a few other collection classes.

I've also just looked at the relevant files in the SSCLI BCL source, and underscores are used there too.

However, it's by no means the same throughout. It looks like different developers on the BCL team used their own standards (bad, bad, naughty Microsoft!), to the extent that some classes have underscore prefixed fields and non-prefixed fields - probably where more than one developer worked on them.

Bottom line is some guys in the CLR team at MS do it that way, some don't. But it's become a reasonably common style particularly in the C# community.
.NET Guy
Wednesday, February 15, 2006
 
 
(Addendum)

A quick find-in-files in *.cs across the CLR source tree within the SSCLI (which is pretty much the same code that shipped in the .NET Framework 1.0) finds over four thousand instances of use of underscore-prefixed fields (and a few private properties too). A few double-underscores from the ex-C++-ers out there, too...

So I can say with certainty that the convention was used within the CLR team, but not universally.
.NET Guy
Wednesday, February 15, 2006
 
 
FWIW, I'm off the "less is more" philosophy.  I disklike having to wade through lots of "clutter" to see what is going on.

Why is it "clutter" -- because it's not necessary.  Borrowing from Strunk & White:

"Vigorous writing is concise. A sentence should contain no unnecessary words, a paragraph no unnecessary sentences, for the same reason that a drawing should have no unnecessary lines and a machine no unnecessary parts. This requires not that the writer make all his sentences short, or that he avoid all detail and treat his subjects only in outline, but that every word tell."

http://www.bartleby.com/141/strunk5.html#13
BillT Send private email
Wednesday, February 15, 2006
 
 
Thinking about it some more, I think part of my impetus to use Me in VB .NET is that, however bad an idea it is, it's still possible to create global methods by putting them in modules and making them public.  So I prefix pretty much any called method with where it came from, whether the current class or a global module.

Personally I don't use global methods, and I try to avoid using modules for anything except perhaps a Main method...but that doesn't mean everyone follows the same rules.

I did a quick test and can confirm that in a VB project, if you have a public method DoSomething in a module and a method of any visibility called DoSomething in a class, the compiler won't emit even a warning.  Calling DoSomething() with no prefix calls the class method, whatever its visibility.  But my personal preference is to avoid the ambiguity completely by using WhateverModule.DoSomething() or Me.DoSomething().

I suppose in general I find scope modifiers less objectionable than type modifiers.  For one thing, you pretty much only need them on class-level variables; whereas if you're denoting type, it ends up being _everywhere_.
Kyralessa Send private email
Wednesday, February 15, 2006
 
 
Personally I prefer the "this" reference at all time.
It is more easy to read and understand. It fixes the scope. In C++ where you have a lot of libraries, namespaces and a lot of other things you are using (for example: STL together with GDI+ and libxml2) you have already a mixup of styles, so giving more exactness to the code is a helper.

And it helps if you develop in more than one language. In PHP you HAVE to use it.

Another thing is: I increased my productivity with Intellisense (or whatever it is called in other IDEs) and typing "this->[ALT-SPACE]" reduces the options very much to the point.

But hey, there are people arguing "m_Var" against "mVar" (not to forget the "m_secondVar" fraction, complaining in the backyard).

If you start working in a company, you should be open minded and good enough to adapt to a _given_ style because you are good as a team, not as a libero.
Husker
Tuesday, February 21, 2006
 
 
I'm rather suprised that anyone mentioned Eclipse as a reason to be in favor of mandator "this."ing, since in Eclipse local variables and member variables are a different color...

One Method, One Task - Since it is generally considered good practice (readability/maintainabilty/extensibility/planning) to keep methods short.  As such, if I'm looking at the code in a method, I can 9.9 times out of 10 SEE the local declarations from where I am.

As such the (ALMOST)only times I've typed "this." in the past year have been to pull up the intellisense list, and then I delete the "this." afterwards to remove clutter.  If someone leaves off or accidentally deletes a this. reference I certainly don't want to munge some field believing that it's only a local...If you don't know whether a variable is local what are the chances you even know what it is and does in the first place?

It would be nice if code-assisting IDEs would all just have a key for "show me a list of objects I can access from this scope".

In conclusion: I think this. references CAN improve readability in some cases (I find them pleasing in setters for instance) but requiring them on all references is even sillier than Hungarian notation.
Crypto Keeper Send private email
Friday, March 03, 2006
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz