Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / May 2007

Tip: Looking for answers? Try searching our database.

enhanced for loop

Thread view: 
visionset - 04 May 2007 20:46 GMT
Why did they decide to restrict the variable scope for enhanced for loops?

It is handy sometimes to have the extra scope.

This won't compile:

String[] strings = {"foo"};

String str;

for (str : strings) {}

Signature

Mike W

Stefan Ram - 04 May 2007 21:13 GMT
>String[] strings = {"foo"};
>String str;
>for (str : strings) {}

public class Main
{ public static void main( final java.lang.String[] args )
 { final java.lang.String[] strings ={ "foo" };
   for( final java.lang.String str : strings ); }}
Jussi Piitulainen - 04 May 2007 21:40 GMT
>> String[] strings = {"foo"};
>> String str;
[quoted text clipped - 4 lines]
>   { final java.lang.String[] strings ={ "foo" };
>     for( final java.lang.String str : strings ); }}

Q. Why is it so?
A. It is so.
visionset - 05 May 2007 01:17 GMT
>>String[] strings = {"foo"};
>>String str;
[quoted text clipped - 4 lines]
>  { final java.lang.String[] strings ={ "foo" };
>    for( final java.lang.String str : strings ); }}

I think you miss my point!
It was a question of scope, not how to construct an enhanced for loop
(despite the subject line).

Signature

Mike W

Stefan Ram - 05 May 2007 01:35 GMT
>I think you miss my point!

 Yes. Sorry.

>It was a question of scope, not how to construct an enhanced for loop

 I see.

 Often the restricted scope will be sufficient.

 Otherwise,

for( i = 0; i < strings.length; ++ i )str = strings[ i ];

 or

for( final java.lang.String s : args ){ str = s; /* ... */ }

 can be used

 When the scope is limited, the loop is better decoupled from
 its anvironment, which might help to refactor the code, e.g.,
 to move the loop to another method.
Lasse Reichstein Nielsen - 05 May 2007 01:54 GMT
> Why did they decide to restrict the variable scope for enhanced for loops?
...
> String[] strings = {"foo"};
>
> String str;
>
> for (str : strings) {}

What is the expected value of "str" after this?
Why?
What if "strings" was the empty array?

I could see the value being the last value assigned, or null, or
unassigned.

If you want to capture the value, just do:

String str = null;
for(String strx : strings) {
  str = strx;
  // ...
}

/L
Signature

Lasse Reichstein Nielsen  -  lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
 'Faith without judgement merely degrades the spirit divine.'

Chris Smith - 05 May 2007 03:17 GMT
> > Why did they decide to restrict the variable scope for enhanced for loops?
> ...
[quoted text clipped - 5 lines]
>
> What is the expected value of "str" after this?

That's a very good question, in general.

> What if "strings" was the empty array?

This seems more obvious to me.  Since the array may be empty, the loop
would certainly not result in str becoming definitely assigned.  So the
obvious behavior would be that an attempt to use it after the loop in
this case would fail; and if str were definitely assigned before the
loop, it would remain the same.

What's less obvious to me is what to do when the variable is definitely
assigned, and there are elements.  In that case, leaving it as the last
element of the array seems like it's letting the implementation leak
through, though I admit it's a minor concern.  After all, if one wants
the last element of the array, one should just get it as strings
[strings.length - 1].

The only case where this expanded scope seems both natural and useful is
when one exits the loop with a break statement and later wants to know
what value caused the break.

Signature

Chris Smith

Patricia Shanahan - 05 May 2007 04:03 GMT
> Why did they decide to restrict the variable scope for enhanced for loops?
>
[quoted text clipped - 7 lines]
>
> for (str : strings) {}

I think the enhanced for statement deals very simply with some very
simple, but common, cases. It does not have all the "handy sometimes"
features it might have, but anything it does not handle can always be
done using a basic for statement.

Patricia
visionset - 06 May 2007 11:50 GMT
>> Why did they decide to restrict the variable scope for enhanced for
>> loops?
[quoted text clipped - 13 lines]
> features it might have, but anything it does not handle can always be
> done using a basic for statement.

That sums it up nicely, and for sure, it is a very minor concern.

The prompt for the question was the typical way boilerplate code is made
more compact by reusing variables, for example with MenuItems.

MenuItem item;

item = new MenuItem("foo");
menu.add(item);
//...
item = new MenuItem("bar");
menu.add(item);
//...
for (item : blah.createMenuItems()) {
   menu.add(item);
}

Signature

Mike W

Lew - 06 May 2007 13:21 GMT
> The prompt for the question was the typical way boilerplate code is made
> more compact by reusing variables, for example with MenuItems.
[quoted text clipped - 10 lines]
>     menu.add(item);
> }

I would recommend not using the same variable in the loop but using a local
one, unless as Patricia said you need the loop value exposed afterward.  There
is too much chance of interaction between code blocks when you don't restrict
the scope of the variable.  The times when you should reuse variables in the
way you show are few and narrowly prescribed.

Signature

Lew

visionset - 06 May 2007 15:53 GMT
>> The prompt for the question was the typical way boilerplate code is made
>> more compact by reusing variables, for example with MenuItems.
[quoted text clipped - 17 lines]
> should reuse variables in the way you show are few and narrowly
> prescribed.

Yes I agree, it was just something that cropped up and made me wonder why
they'd forced the declaration.

Signature

Mike W

Daniel Pitts - 08 May 2007 06:38 GMT
> >> Why did they decide to restrict the variable scope for enhanced for
> >> loops?
[quoted text clipped - 34 lines]
> --
> Mike W

Eeew! I HATE code like that with a passion!

I try my best to create all local references as final, so that I know
that they won't be changed on me somewhere in the code.  Your code is
the exact opposite of that goal :-)

Seriously, its bad form to reuse variables.  If you have a good enough
IDE (Eclipse, or IDEA for instance) you won't need to use such
dangerous boilerplate code.
visionset - 08 May 2007 11:36 GMT
>> The prompt for the question was the typical way boilerplate code is made
>> more compact by reusing variables, for example with MenuItems.
[quoted text clipped - 11 lines]
>>
>> }

> Eeew! I HATE code like that with a passion!
>
[quoted text clipped - 5 lines]
> IDE (Eclipse, or IDEA for instance) you won't need to use such
> dangerous boilerplate code.

Well for almost all other code I agree, but it has it's place, and I don't
regard it as in the least bit dangerous for the use above.  The goal is
compact code to make the long winded process of gui configuration clearer.
Reusing a variable as above says as self documenting code, this is a trivial
local variable thats only merit is inplace config, after which swings
internals take care of tracking the reference.  Self documenting code is
good, the code above used as it is, is therefore good.

Signature

Mike W

Lew - 08 May 2007 13:41 GMT
"Daniel Pitts" wrote
>> Eeew! I HATE code like that with a passion!
>>
[quoted text clipped - 13 lines]
> internals take care of tracking the reference.  Self documenting code is
> good, the code above used as it is, is therefore good.

That is, of course, your opinion and you're entitled to it.

Others would disagree.

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.