The Recursive Context Adapter idiom

Sometimes it makes sense to allow a method a default value for one or more of its parameters. Sometimes, because the parameter is a complex, user-defined type, it doesn’t make sense to hard-code its construction sequence in the parameter list. Consider this example:

void Widget::Resize(Rectangle* pRect /* = NULL */)
{
  static const Rectangle default(100, 100, 100, 100);
  if (pRect == NULL)
  {
    // Use default
    pRect = &default:
  }

  // Do resize
}

I’m not too happy with this code. There’s some unbalanced quality to it that I don’t care for. I ran into a case like this once, and came up with this technique:

void Widget::Resize(Rectangle* pRect /* = NULL */)
{
  if (pRect == NULL)
  {
    // Use default
    Rectangle r(100, 100, 100, 100);
    Resize(&r); // recurse!
  }
  else
  {
    // Do resize
  }
}

It’s so simple and succinct, and can actually be used for various other flow-of-control adjustments besides parameter defaults. Based on some contextual circumstance, you can change some aspect of the flow, and run the method again. This is a strictly controlled way of using recursion that actually helps readability. I didn’t think that was possible.

It seems to be generally applicable, so I’ve decided to dub it the Recursive Context Adapter idiom. The name alludes to the fact that it’s recursive, and that it adapts the context of the method before running it for real.

Kommentera

Fyll i dina uppgifter nedan eller klicka på en ikon för att logga in:

WordPress.com Logo

Du kommenterar med ditt WordPress.com-konto. Logga ut / Ändra )

Twitter-bild

Du kommenterar med ditt Twitter-konto. Logga ut / Ändra )

Facebook-foto

Du kommenterar med ditt Facebook-konto. Logga ut / Ändra )

Google+ photo

Du kommenterar med ditt Google+-konto. Logga ut / Ändra )

Ansluter till %s