Incremental Java
Prioritized if

Prioritized if

We came up with this example of a nested if, where the if appears in the else body.
if ( num > 90 )
{
  System.out.println( "You earned an A" ) ;
}
else
   if ( num > 80 )
   {
      System.out.println( "You earned a B" ) ;
   }
   else
      if ( num > 70 )
      {
         System.out.println( "You earned a C" ) ;
      }
This kind of code appears quite often. Basically, you have a series of conditions. It evaluates one condition after another until it reaches one that evaluates to true, and then runs the body, and exits to the next statement after this entire structure.

I call this a prioritized if. That's because it checks the first condition (which has the highest priority), then the second, then the third and so forth. It's sort of like asking someone to a dance. You may make a list of several candidates and rank them from 1 to N. You stop asking when the highest ranked person says yes.

A Nicer Way To Write Prioritized if

Java doesn't care about indentation, so we can rewrite it as:
if ( num > 90 )
{
  System.out.println( "You earned an A" ) ;
}
else if ( num > 80 )
{
   System.out.println( "You earned a B" ) ;
}
else if ( num > 70 )
{
   System.out.println( "You earned a C" ) ;
}
This, I believe, is much easier to read. To the compiler, it's the same code, but to a human reader, I think it's easier to read.

The general structure is:

if ( cond 1 )
   if body 1
else if ( cond 2 )
   else if body 2
else if ( cond 3 )
   else if body 3
else // final else---optional
   else body
You can have zero or more of the else if lines and its associated body. The final else is optional.

In a prioritized if, you run the body of the highest priority condition that evaluates to true. This evaluation is done from the top condition to the bottom, stopping at the first one that evaluates to true

If you have a final else, then exactly one body is guaranteed to run. If you don't, then at most one is guaranteed to run (it's possible all the conditions evaluate to false and none run).

Again, the prioritized if is nothing special in Java. It's normal nested if, but just indented in a way to make it easier to read.