Download DB2

Dividing code into functions

April 9th, 2007 by Leons Petrazickis

Functions are methods are procedures are subroutines. They are blocks of code that are called and that call each other. They can be divided into classes or modules, but their nature remains the same.

Most of the time, a poorly designed function is too long and monolithic. An oversized function is micromanaging too many details, making it hard to read, and not encapsulating repetitive operations enough, making it harder to expand and revise.

Delegate to Other Functions

Don’t let your big picture function get bogged down in the details. If you are marshaling resources across an application, don’t get side-tracked customizing a single parameter.

page = Page();
title = "Monkey";
title = "(" + title + ") ";
title += str(23);
page.title = title;
page.display();
 

Code is read much more often than it is written, so plan accordingly! What’s wrong with the above? Its topic is very high level, but 5/7 lines are spent micromanaging a single parameter. You need to delegate that:

def makeTitle(core, number):
  title = core;
  title = "(" + title + ") ";
  title += str(23);
  return title;

page = Page();
page.title = makeTitle("Monkey", 23);
page.display();
 

Now that the details are hidden, the big picture is much easier to manage. Generally, when several lines of your function body take several things to reach a single answer, they belong in a function of their own.

Put Complex Operations into Functions

If you are doing the same data munging operation all over the place, abstract it away into a function. Not only is a well-named function call clearer than the actual operation, but you’ll also make it easy for yourself to change the operation down the road. A function created with foresight will save you from a complex Find-and-Replace regex dance.

This is surely old hat to experienced coders and refactorers

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Reddit

Posted in opinion |

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.