Composing Methods: Substitute Algorithmn

Posted by Tim Koschützki, on Aug 15, 2007 - in Coding Techniques & Tools » Refactoring

When you want to replace an algorithmn with one that is clearer, replace the body of the method with the new algorithmn.

Motivation

This often does not appear as a real refactoring. However, "Substitute Algorithmn" should not be underestimated. It's really something we should do all the time.
If you find a clearer way to accomplish something, you should replace the complicated way with the easier one.

Remember this important statement: "Do the simplest possible thing." Designing systems is so hard already - why should you go out of your way to make the task even harder?
Break complex things up into simpler things, and let each solve a piece of the puzzle. Gaius Julius Cesar had the right idea with his "Divide and Conquer" approach.

Programming is such a dynamic action that you often find yourself having to replace an algorithmn alltogether. It will be much easier to do if the current algorithmn is an easy one already.
Also, you may start using a library and thus your code may be subject to duplication. Substitute the corresponding algorithmns and get rid of the duplication.

Make sure you decompose your algorithmns as much as you can and use many small methods for it.

Mechanics

  • Prepare your alternative algorihtmn.
  • Run your new algorithmn against your unit tests. If the results are the same, you are finished.
  • If the results are not the same, run each test case with the old a new algorihtmn and solve those that fail.

Example

Before:

php
  1. function foundPerson($people = array()) {
  2.   $numPeople = count($people);
  3.   for($i=0;$i<$numPeople;$i++) {
  4.     if($people[$i] == "Tim") {
  5.       return "Tim";
  6.     }
  7.     if($people[$i] == "Felix") {
  8.       return "Felix";
  9.     }
  10.     if($people[$i] == "John") {
  11.       return "John";
  12.     }
  13.   }
  14.   return "";
  15. }

After:

php
  1. function foundPerson($people = array()) {
  2.   $numPeople = count($people);
  3.   $candidates = array("Tim", "Felix", "John");
  4.  
  5.   for($i=0;$i<$numPeople;$i++) {
  6.     if(in_array($people[$i], $candidates)) {
  7.       return $people[$i];
  8.     }
  9.   }
  10.   return "";
  11. }