go to previous page   go to home page   go to next page highlighting

Answer:

Yes. The code compiles.

public class UnitTestBad
{
  static int N = 10;
  
  public static long factorial( )
  {
    long fct = 1;
    for ( int j=1; j<=N; j++ )
      fct *= j;
    return fct;
  }
  
  public static void main (String[] args ) 
  {
     System.out.println( "factorial of " + N + ": " + factorial() );
  }
}

Global Variable

The code compiles and runs correctly. But now the scope of the class variable N is the entire program. This is dangerous. A variable who's scope extends over the entire program is sometimes called a global variable.

Global variables often cause unexpected interactions between parts of a program that should be independent. In a tiny program like this one, problems are unlikely. But in big programs uninteded interactions are a common bug.

Examine the following code. Notice the alternative calculation of factorial. Looks fine. What could go wrong?


public class UnitTestBadBad
{
  static int N = 10;
   
  public static long factorialAlt()
  {
    long fct = 1;
    while ( N>0 )
    {
      fct *= N;
      N-- ;
    }
    return fct;
  }
  
  public static void main (String[] args ) 
  {
     long result = factorialAlt();
     System.out.println( "factorial of " + N + ": " + result );
  }
}


C:\Source> java UnitTestBadBad factorial of 0: 3628800

QUESTION 13:

What went wrong?


go to previous page   go to home page   go to next page