Posted by: terryhowe | October 2, 2009

Clean Code: Functions

The functions chapter of Robert C. Martin’s Clean Code causes no great epiphany, but it is a good review. Some of the interesting points include:

  • Small:  Obviously, functions should be small.  Ideally, they should be small enough that you can see the entire thing on one screen.
  • Blocks and Indenting:  It is rare to see somone not use indenting for blocks.  I could care less where the curly brace goes, but I generally don’t like taking up extra vertical space with the curly brace on its own line.
  • Do One Thing:  If your function only does one thing, it will be small.
  • One Level of Abstraction per Function:  A good way to break up large functions keep code together that is at the same level abstraction.  Move the lowest level of abstract out first.
  • Reading Code from Top to Bottom:  People read from top to bottom, so organize the functions so that they make the most sense read from top to bottom.  The highest level of abstraction should be at the top.
  • Switch Statements:  Switch statements might be a sign that you should use inheritance to solve the problem
  • Function Argument:  Generally, the idea is that the fewer the arguments, the better.  If there are more than one or two arguments, it probably should be done some other way.  Flag arguments can easily be avoided.
  • Command Query Separation: Functions should either do something or answer something, but not both.
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: