| Author |
is it ok to assign the the local object reference variable to null ?
|
mike zhang
Ranch Hand
Joined: Feb 26, 2002
Posts: 59
|
|
local variables have to initialized. is it ok to assign them to null always ? for example, is the code below ok ? [ May 28, 2002: Message edited by: Dirk Schreckmann ]
|
 |
Jason Kretzer
Ranch Hand
Joined: May 31, 2001
Posts: 280
|
|
IMHO, it is perfectly fine to do so. I use this code all the time---particularly with initializing private data members in a class' constructor. HTH,
|
Jason R. Kretzer<br />Software Engineer<br />System Administrator<br /><a href="http://alia.iwarp.com" target="_blank" rel="nofollow">http://alia.iwarp.com</a>
|
 |
Rob Ross
Bartender
Joined: Jan 07, 2002
Posts: 2205
|
|
|
Well, you have to initialize your local variables at some point, so this is fine. In fact, it's a pretty good idea to initialize object references to null, since this is what happens for member variables when a new class is constructed.
|
Rob
SCJP 1.4
|
 |
Michael Matola
whippersnapper
Ranch Hand
Joined: Mar 25, 2001
Posts: 1722
|
|
It's possible that I don't 100% understand the question or the intent of the code. But anyhow, for what it's worth, here's how I'd write that code: (1) If all you're doing is returning an instance of MyClass and not doing anything else with that instance within this method, then why bother declaring the identifier "myClass" at all, let alone worrying about whether to set it to null? (2) "return myClass = new MyClass();" -- Sure it's valid syntax, but is anyone really advocating this as good style? (3) I reversed the condition because it makes it clearer to me that throwing the exception is the exceptional behavior and returning the new instance of MyClass is the standard behavior. (Others might object that testing for a negative is a bad thing...)
|
 |
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
|
|
|
Looks much cleaner to me, Mike. Testing for the negative is fine IMO because you don't have an else block that way.
|
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
|
 |
 |
|
|
subject: is it ok to assign the the local object reference variable to null ?
|
|
|