Hi,
I haven't come accross an elegant solution to a design problem that I show below. Have a look at the piece of code here:
There is a problem with this code. Let me first tell you my intentions. I want to use the variable 'e' ( of type 'Exc' ) only inside the for loop. That is, I want to restrict its scope to the for loop. So I have declared it inside the loop. But I also want to initialize it with a new object of type 'Exc'. So I have written a declaration cum initializer statement. But since the statement is inside the for loop, it gets executed multiple number of times ( 4 times to be precise ). My intention was to have it executed only once.
There is one solution to this problem which is to use a counter or a sentinel that will signal the number of times that the loop has executed. Fortunately here, the for loop is using a 'built-in' counter namely 'i'. So the code now becomes:
Another solution for this would be to enclose the for loop inside a code block delimited by '{' and '}' and declare the variable 'e' outside the for loop but inside the code block. The variable 'e' will also be initialized when it's declared. Here's what I mean:
This way the variable 'e' will have its scope restricted to the for loop and also be 'initialized' only once.
But these solutions are somewhat artificial. Their design intentions are not immediately clear. Are there any elegant solutions for this design problem - something that is naturally expressed by the Java language ?
I haven't come accross an elegant solution to a design problem that I show below. Have a look at the piece of code here:
Code:
class Exc
{
Exc ()
{
System.out.println ("Haribol");
}
static public void main ( final String [] args )
{
for ( int i = 0 ; i < 4 ; ++ i )
{
Exc e = new Exc ();
}
}
}
There is one solution to this problem which is to use a counter or a sentinel that will signal the number of times that the loop has executed. Fortunately here, the for loop is using a 'built-in' counter namely 'i'. So the code now becomes:
Code:
class Exc
{
Exc ()
{
System.out.println ("Haribol");
}
static public void main ( final String [] args )
{
for ( int i = 0 ; i < 4 ; ++ i )
{
Exc e;
if ( i == 0 ) e = new Exc ();
}
}
}
Code:
class Exc
{
Exc ()
{
System.out.println ("Haribol");
}
static public void main ( final String [] args )
{
{
Exc e = new Exc () ;
for ( int i = 0 ; i < 4 ; ++ i )
{
//call some methods on 'e'
}
}
}
}
But these solutions are somewhat artificial. Their design intentions are not immediately clear. Are there any elegant solutions for this design problem - something that is naturally expressed by the Java language ?
Comment