Execution equivalence:

Two pieces of code are "execution equivalent", if in ALL possible scenarios for the starting state at the beginning of the code, the end state after the code is executed is identical for both pieces of code.


Top factoring:  if the beginning statements in the THEN and in the ELSE are identical, can they be moved to BEFORE the if test?    

Are the following equivalent?
if (facingSouth())
{
   move();
   turnLeft();
}
else
{
   move();
   turnRight();
}   
move();
if (facingSouth())
{    turnLeft();
}
else
{   turnRight();
}


if (nextToABeeper())
{
   move();
   turnLeft();
}
else
{
   move();
   turnRight();
}
move();
if (nextToABeeper ())
{    turnLeft();
}
else
{   turnRight();
}




Bottom factoring:  if the ending statements in the THEN and in the ELSE are identical, can they be moved to AFTER the if-else statement?

Are the following equivalent?

if (facingSouth())
{
   turnLeft();
   move();
}
else
{
   turnRight();
   move();
}
if (facingSouth())
{    turnLeft();
}
else
{   turnRight();
}
move();




Redundant test elimination:   Are any of the predicate tests (in a loop or in an if) unnecessary, in that we always know whether it is true or false?

Are the following equivalent?

if (facingSouth())
{    turnLeft();
}
else
{   if (! facingSouth())
          turnRight();
}
move();
if (facingSouth())
{    turnLeft();
}
else
{   turnRight();
}
move();


while (nextToABeeper())
{  
   if (nextToABeeper())
          pickBeeper();
}   
while (nextToABeeper())
{  pickBeeper();
}



while (nextToABeeper())
{  
   move();
   if (nextToABeeper())
          pickBeeper();
}
while (nextToABeeper())
{  move();
   pickBeeper();
}



Exercise: Can you come up with code that is Execution Equivalent to the following but shorter?


if (facingSouth())

    turnLeft();
    if (facingNorth())
       turnLeft();
   else
       move();
}
else
{
    move();
    while (facingSouth())
   { 
        turnLeft();
        if (nextToABeeper())
       {
            move();
            turnLeft();
        }
       else
       {
            move();
            turnRight();
        }  
    }
    move();
}