TITLE: I Go To Extremes AUTHOR: Eugene Wallingford DATE: January 24, 2005 10:01 AM DESC: Taking practices to an extreme can teach us a lot about how to use them correctly. ----- BODY: Brian Button recently posted a long blog entry on his extreme refactoring of the video store class from Martin Fowler's Refactoring. Brian "turned [his] refactoring knob up to about 12" to see what would happen. The result was extreme, indeed: no duplication, even in loops, and methods of one line only. He concluded, "I'm not sure that I would ever go this far in real life, but it is nice to know that I could." Turning the knobs up in this way is a great way to learn something new or to plumb for deeper understanding of something you already know. A few months ago, I wrote of a similar approach to deepening one's understanding off polymorphism and dynamic dispatch via a simple etude: Write a particular program with a budget of n if-statements or less, for some small value of n. As n approaches 0, most programmers -- especially folks for whom procedural thinking is still the first line of attack -- find this exercise increasingly challenging. Back at ChiliPLoP 2003, we had a neat discussion along these lines. We were working with some ideas from Karel the Robot, and someone suggested that certain if-statements are next to impossible to get rid of. For example, How can we avoid this if?
     public class RedFollowingRobot
     {
         public void move()
         {
             if (nextSquare().isRed())
                 super.move();
         }
     }

     public class Square
     {
         public boolean isRed()
         {
             ...
         }
     }
But it's possible... Joe Bergin suggested a solution using the Strategy pattern, and I offered a solution using simple dynamic dispatch. You can see our solutions at this wiki page. Like Brian said in his article, I'm not sure that I would ever go this far in real life, but it is nice to know that I could. This is the essence of the powerful Three Bears pattern: Often, in taking an idea too far, we learn best the bounds of its application. Joe and I like this idea so much that we are teaching a workshop based on it, called The Polymorphism Challenge (see #33 there) at SIGCSE next month. We hope that spending a few hours doing "extreme polymorphism" will help some CS educators solidify their OO thinking skills and get away from the procedural way of thinking that is for many of them the way they see all computational problems. If you have any procedural code that you think simply must use a bunch of if-statements, send it to me, and Joe and I will see if it makes a good exercise for our workshop! -----