Python Rocks! and other rants
Weblog of Kent S Johnson

2004-04-04 14:44:16

Short methods

I write code in a highly factored style. Part of this is keeping methods short. There are several advantages to small methods:

  • Short methods are easy to understand
  • Client code becomes a series of method calls. If the methods are well named it is easy to follow what is happening.
  • This leads to layered code. It can be very fast to find the place where a change is needed.
  • Fine-grained code is often easier to change.

There are also disadvantages to this style:

  • It can be hard to trace the flow of execution when it goes through many layered methods distributed across several classes.
  • Adding an option to a low-level method can require changes to many methods in the levels above it.

But on balance I think short methods are very helpful.

Short methods are a powerful technique for writing self-documenting code. When writing a block of code that needs a comment to explain it, consider putting the block in a separate method whose name makes the comment redundant.

 
© Kent S Johnson Creative Commons License

Comments about life, the universe and Python, from the imagination of Kent S Johnson.

kentsjohnson.com

Weblog home

All By Date

All By Category

Essays

XML-Image

BlogRoll