If condition A is matched, condition B needs to be matched in order to do action C

starf15h picture starf15h · Jul 20, 2017 · Viewed 12.7k times · Source

My question is:

if (/* condition A */)
{
    if(/* condition B */)
      {
         /* do action C */
      }
    else
      /* ... */
}
else
{
   /* do action C */
}

Is it possible to just write the code of action C one time instead of twice?

How to simplify it?

Answer

QuestionC picture QuestionC · Jul 20, 2017

Your first step in these kinds of problems is always to make a logic table.

A | B | Result
-------------------
T | T | do action C
T | F | ...
F | T | do action C
F | F | do action C

Once you've made the table, the solution is clear.

if (A && !B) {
  ...
}
else {
  do action C
}

Do note that this logic, while shorter, may be difficult for future programmers to maintain.