wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes No visual difference between member and local variables? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "No visual difference between member and local variables?" Watch "No visual difference between member and local variables?" New topic
Author

No visual difference between member and local variables?

J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Hi!

Consider the following:


This actually prints

theClassVar
5

Surely I am missing something, cause I am so used to Self.classVar or this.classVar notation that I find it impossible to believe there is no such notation in Java, worse one can overwrite class members so easily...

I think this makes it really hard to read code, there is no visual difference between member and local variables.

I have to admit though that I am only at chapter 5 of HeadFirst Java, but I was so stunned when I found this out that I figured I had to come here (as suggested by the book) and ask.

Thanks a lot in advance for your time and patience!

Greetings,
J�rgen
[ March 05, 2006: Message edited by: J�rgen Hauser ]
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
In this first line of the method, since there is no local variable with that name, implicitly classVar is the same as this.classVar. After we declare a local variable with the same name as an instance variable, it shadows the instance variable. After that declarations, any reference to classVar is to the local variable classVar. If you want to refer to the instance variable after that declaration, you have to use this.
J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Ah I see, thanks!

(still think it's weird that it is possible to access class members without this. whereas we have to preceed the classname when creating a new instance, as in TheClass theClass = new TheClass(); You'd think that since you are assigning the TheClass to the variable it should automatically be of type TheClass, ...)

So is it a standard or considered good practice to use "this" to access class members or do I need to expect to find tons of classes where you can't visually differentiate between them? (Am I the only one who thinks this makes it really hard to read code?)

[ March 04, 2006: Message edited by: J�rgen ]
[ March 04, 2006: Message edited by: J�rgen ]
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by J�rgen:
[QB]Ah I see, thanks!

(still think it's weird that it is possible to access class members without this. whereas we have to preceed the classname when creating a new instance, as in TheClass theClass = new TheClass(); You'd think that since you are assigning the TheClass to the variable it should automatically be of type TheClass, ...)


Because of inheritance, a class of type TheClass does not necessarily have to have a reference of type TheClass. The reference type can be the class or any of its superclasses.

So is it a standard or considered good practice to use "this" to access class members or do I need to expect to find tons of classes where you can't visually differentiate between them? (Am I the only one who thinks this makes it really hard to read code?)


Usually you don't write this unless there is a potential of confusion with a local variable.
[ March 04, 2006: Message edited by: Keith Lynn ]
J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Alright, ....

Thanks!
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
First of all, my personal preference is to use "this.classVar" when referencing member variables (always). As your subject title says, this gives a visual clue that the variable is an instance variable, not a local variable. Note that just because you didn't use this syntax in your example does not mean that it doesn't exist as you implied in your original post. Perhaps unfortunately, it is optional to use the "this" keyword.

Second, as Keith described, the reference type and the actual object type do not need to match exactly. For example, you could do

In fact, this is a common practice in many situations. A recent thread here at the Ranch discusses a similar situation that arises when using the Collection framework:

Since Vector implements the List interface, you can assign a List reference to point to a Vector object. As you learn more about Java you will see this more and more. This follows the common paradigm called "code to the interface".

I hope this clears things up for you. Good luck and keep coding!

Layne
[ March 04, 2006: Message edited by: Layne Lund ]

Java API Documentation
The Java Tutorial
J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Hi!

I am glad to hear I am not alone on the "this" issue.

I agree with you on the design principle of always programm (try to ) to an interface.

Consider the following example:

Assume we have a class called ArticlesValidator which extends a class Validator which in return implements an interface called IValidator (I know by some it is considered bad practice to prefix interfaces with I, but let's ignore this for now)

What is the point of being forced to write the following:



Would it not make a lot more sense to have the variable articlesValidator be of type ArticlesValidator by default? I think this would save A LOT of typing.



Now I am probably going ahead of myself (and the book) but isn't the instance variable articlesValidator supposed to be of type Validator automatically too? (right after I finish writing this I'll test it to find out)

Either way, to continue using your example of List and Vector



Anyway, don't get me wrong, I am just questioning WHY in order to better understand

(Marilyn broke up long comment line in the "code")
[ March 04, 2006: Message edited by: Marilyn de Queiroz ]
J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Alas, I failed to quickly find how to check the type of a variable (google didn't help either), and I have to go now, I'll be back tommorow and post my results (even if obvious to most, someone might benefit)

(Perhaps someone can point me in the right direction of how to find the type of a class? assertIsA(obj, 'TheClass') ?
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
Hi, J�rgen,

Welcome to JavaRanch! Please adjust your display name to meet the JavaRanch Naming Policy.
You can change it here.

Thanks!

Now, on to your question.
You must declare the reference type that the new object is pointing to. The reference type may or may not match the object type. The reference type may be the same type as the object or may be a superclass of the object. It may not be a subclass of the object.

To find out whether Vector is a type of List before you write this code

You can write

Or you can look in the API and see that Vector implements List.

The advantage of writing
List list = new Vector();
is that you can easily make the reference "list" point to a different type of List without changing the way "outsiders" see the code. i.e.
List list = new ArrayList();
If you have only used the methods in the List class, you probably need to make no other changes in your code.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by J�rgen:
I am glad to hear I am not alone on the "this" issue.


Well, this is very common for people coming from Smalltalk...

If you are used to it, it typically proves to be not much of a problem - especially with modern IDEs.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Indeed: IDEs will highlight members and locals in different colors for you.

People who came up through C++ (which works the same as Java in this regard) think that having to say "self" or "this" for every member reference is an ugly hack!

That said, you can read this blog entry I wrote a short while back, explaining why I still like to use "scope warts", even though most of my fellow Java-ites don't appreciate them.
[ March 04, 2006: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Hello Marilyn!

Thanks a lot, as requested I changed the display name to include lastname as well.

I certainly understand the advantages of casting a reference to be of a type List, however, the question I asked was

What's the point of being forced to do


Why isn't the reference vector by default the type of the class I use to create the reference? Okay asking why might be wrong, because obviously it's been implemented like this so we have to do it, but I fail to see ANY advantage.

Is there any advantage?

Hello Ilja!

There you go, I didn't know IDE's visually colorize the difference between local and member variables, and whilst this MIGHT be a little help, I still believe that using this makes it a lot clearer and totally IDE independant ( not to mention that one IDE will use different colors then the other etc..., and as it is I think syntax highlighting has enough colors).

Hello Ernest!

I read your blog entry, and personally I favor using this above using prefixes, because prefixes truly feel like a workaround, whereas "this" is a language feature and makes a whole lot of sense.

I strongly disagree that using "this" means more typing, I can create a macro, assign a key to it and with one press I have "this." wherever I need it.

To conclude, I certainly see the advantage of casting a reference to a certain type (especially with Decorators and Visitors), I think it's truly a shame that the use of "this" isn't a requirement, and I'm hoping there is an advantage of being forced to declare the type of a reference that should be obvious by default.

And now, I'm going to continue reading the heads first book (which is truly so much fun to read, and, oh, looks like it's going to teach quite a bit too).

Greetings,
J�rgen
[ March 04, 2006: Message edited by: J�rgen Hauser ]
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by J�rgen Hauser:
What's the point of being forced to do


Why isn't the reference vector by default the type of the class I use to create the reference?


Funny that you ask. It's really for a similar reason that you want to write "this" in front of every field - it forces you to be more explicite about what you actually mean (and supposedly thereby catches some possible mistakes).

My point about the IDE really was a minor one - the important thing is that there are good arguments for both sides, and lastly it really comes down to personal preference - to what you are used to.

Not putting "this" in front of every field might sound insane to you, but if you are used to it, it proves not to be a big problem (especially if you write unit tests for your code).

People used to static typing feel similarly uncomfortable about dynamic typing, although I'd assume that the problems again aren't as big as they fear.
J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Hello!

I don't mean to nitpick, but how is


not explicit enough compared to


Oh well, guess I'll have to live with it.

By the way, I have worked (and still am) 5 years with a dynamically typed language, and indeed there is nothing at all to be feared.

Anyway, thanks for your time
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[J�rgen]: I agree with you on the design principle of always programm (try to ) to an interface.

I would elaborate on this a bit - try to program to the most general interface that is specific enough to meet your needs. Because that makes it easier to change implementations later if you need to, or to reuse your code in a different context. Your suggestion that the compiler should infer the type Vector for variable vector runs counter to this. That is, you are proposing that the compiler should infer the most specific type possible, namely the concrete class Vector. I think that's overly specific for most applications, and you would probably be better off if the variable were treated as a List, Collection, or even Iterable (in JDK 5). What happened to programming to an interface?

Java is a strongly-typed language, and its syntax is set up to require you to explicitly state a type for most things, rather than let the compiler infer a type. The advantages of this, IMO, are that (a) the forced declaration is also an opportunity for you to specify a more appropriate level of abstraction for the type (e.g. choosing a Collection or List rather than Vector), and (b) it makes the type obvious for all programmers who see the code; they don't need to know details of how the type might have been inferred. Instead it's clearly specified in the code.

Now, there are many cases where Java's propensity for long class and interface names leads to code that looks unneccessarily verbose. There are many times when

looks a bit tiresome to me too; I see the appeal of dynamic typing here. But forcing an explicit declaration does have some benefits, allowing us to be flexible about what type we choose to declare, while also being very clear about what the type is. That's the idea, anyway. Your mileage may vary, and all that.
[ March 05, 2006: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jim Yingst:
But forcing an explicit declaration does have some benefits, allowing us to be flexible about what type we choose to declare, while also being very clear about what the type is.


Not only that, it also prevents bugs like the following:



In Java, that doesn't compile - in J�rgen's version it would.

Whether that's worth the extra verboseness still is debatable, of course.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by J�rgen Hauser:
By the way, I have worked (and still am) 5 years with a dynamically typed language, and indeed there is nothing at all to be feared.


I'll believe you - if you'll believe me that there is nothing to be feared about supressing the "this" prefix for fields...
J�rgen Hauser
Greenhorn

Joined: Mar 04, 2006
Posts: 10
Hi Jim!

Thanks, point taken

@Ilja

Ilja, all I fear when supressing this for members is readability and easily introducing possible bugs. It's one thing if you will be the only person who ever needs to read your code, but if others need to read a completely strange class then I thinks this makes it easier (Alright already, of course I know that ideally there should be some sort of API documentation available, and usually if I'm the Author there will be, and that could be used to "read" the class..., but many times there is no API docs ... )

I have to admit that I am still a bit suprised that the use of "this" is optional, but oh well, things could be worse

Despite the little startup hicks and suprises I hope the rest of my journey into Java will be fun, and I truly look forward to explore more of the available API. (I'm also very curious about GUI creation even if I have to admit that sofar I have not met anybody who raves about Swing and I forgot what the other one was named, but I guess I will soon enough know. (I've heard some not so fun stories about positioning widgets and the like...)

Also, javaranch seems to be one of those very very rare communities where folks are civilized and friendly. A pleasant suprise, I have to say.

Cheers,
J�rgen

Ps: Now the only thing missing is more time!

[ March 05, 2006: Message edited by: J�rgen Hauser ]
[ March 05, 2006: Message edited by: J�rgen Hauser ]
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by J�rgen Hauser:
javaranch seems to be one of those very very rare communities where folks are civilized and friendly. A pleasant suprise, I have to say.


Thank you. We work hard to keep it this way!
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by J�rgen Hauser:
Hello!

I don't mean to nitpick, but how is


not explicit enough compared to




Umm...perhaps because the type is explicit, not implied.

I also agree with Ilja that, without the explicit type for the reference, you can create potential bugs if you mistype the name of the variable.

Layne
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by J�rgen Hauser:
Ilja, all I fear when supressing this for members is readability and easily introducing possible bugs.


Yes, I understand.

But frankly, if your methods are huge enough that you have trouble telling whether a variable is declared locally, you have bigger problems than a missing "this" prefix. Seriously.

(Alright already, of course I know that ideally there should be some sort of API documentation available, and usually if I'm the Author there will be, and that could be used to "read" the class..., but many times there is no API docs ...


Mhh, I wouldn't count on API doc here, anyway. JavaDoc is nice to document the interface of a class or package when the source code isn't published, but to really understand the internals of a method, I typically prefer to read the code itself.

I have to admit that I am still a bit suprised that the use of "this" is optional, but oh well, things could be worse


I can imagine. Statically typed languages feel very differently from dynamically typed ones, and what ever you are used to, the other world will sound kinda scary on your first visits.

(I'm also very curious about GUI creation even if I have to admit that sofar I have not met anybody who raves about Swing and I forgot what the other one was named, but I guess I will soon enough know. (I've heard some not so fun stories about positioning widgets and the like...)


Just don't touch GridBagLayout, and everything will be fine...


Also, javaranch seems to be one of those very very rare communities where folks are civilized and friendly. A pleasant suprise, I have to say.


As Ernest said, there is some work involved in keeping it that way. But posts such as yours make it all worthwhile!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: No visual difference between member and local variables?
 
Similar Threads
Local Inner class
Access to static vs. local variables named the same
Variables in Java
what is difference between
Wondering why this works the way it does....