JMU
Boolean Methods
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Boolean Methods
Indicating Success/Failure
Indicating Success/Failure (cont.)
public static boolean printSquareRoot(double x)
{
  boolean    ok;
  double     squareRoot;

  if (x >= 0.) 
  {
    squareRoot = Math.sqrt(x);
    JMUConsole.printf("The root of %f is %f.\n", x, squareRoot);
    ok = true;
  } 
  else 
  {
    ok = false;
  }


  return ok;
}
  
Test Methods
An Example of a Test Method
An Example of a Test Method (cont.)
The Benefits of Test Methods
The Benefit of Reducing Code Duplication
The Benefit of Reducing Code Duplication (cont.)
The Benefit of Reducing Code Duplication (cont.)
Related/Similar Test Methods
Related/Similar Test Methods (cont.)
Boolean Methods are Not Always Appropriate
Boolean Methods are Not Always Appropriate (cont.)
One Implementation
public static boolean isPassing(int grade)
{
  return grade>=60;
}

public static int creditsEarned(int grade, int creditsPossible)
{
  if (isPassing(grade)) return creditsPossible;
  else                  return 0;
}
An Alternative Implementation
public static int isPassing(int grade)
{
  return grade/60;
}

public static int creditsEarned(double grade, int creditsPossible)
{
  return isPassing(grade)*creditsPossible;
}