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:
Expand|Select|Wrap|Line Numbers
- 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:
Expand|Select|Wrap|Line Numbers
- 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 ();
- }
- }
- }
Expand|Select|Wrap|Line Numbers
- 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 ?