Inversion in Programming Languages is where you change the order of statements in part of a method or function.

Example before inversion:

int filterNumber(int number){
  if(number % 2){
    return number;
  }

  return 0;
}

int calculate(int bottom, int top){
  if (top > bottom){
    int sum = 0;

    for (int number = bottom; number <= top; number++){
      sum += filterNumber(number);
    }
    return sum;
  } else {
    return 0;
  }
}

Example after inversion:

int filterNumber(int number){
  if(number % 2){
    return number;
  }

  return 0;
}

int calculate(int bottom, int top){
  if (top < bottom){
    return 0;
  }

  int sum = 0;

  for (int number = bottom; number <= top; number++){
    sum += filterNumber(number);
  }
  return sum;
}

We have:

  • reversed the condition to exit early
  • the for loop is only reached if the guard clause is not satisfied

following this pattern in complex code with lots of conditions usually results in quite a few of these “guard clauses” at the start of a method of function. The error paths appear at the top and the “happy path” gets moved further down.