Disclaimer

The content of this blog is my personal opinion only. Although I am an employee - currently of Nvidia, in the past of other companies such as Iagination Technologies, MIPS, Intellectual Ventures, Intel, AMD, Motorola, and Gould - I reveal this only so that the reader may account for any possible bias I may have towards my employer's products. The statements I make here in no way represent my employer's position, nor am I authorized to speak on behalf of my employer. In fact, this posting may not even represent my personal opinion, since occasionally I play devil's advocate.

See http://docs.google.com/View?id=dcxddbtr_23cg5thdfj for photo credits.

Saturday, September 16, 2006

Refactoring returns by introducing booleans

Consider code that looks like:
  1. void foo() {
  2. if( some-condition ) return;
  3. if( some-other-condition ) { do-something; return; }
etc.

Say this code is replicated in several places. Obviously we want to extract it into a common subroutine or class - the extract method refactoring.

If you can jump right to the end of the refactoring, great. But, I admit that I have occasionally tripped myself up doing this. (The example is, of course, oversimplified.)

So, here's a micro-refactoring that can help:

Extract to a function that returns a bool, named check_and_do_some_things_and_maybe_return()


  1. void foo() {
  2. if( check_and_do_somethings_and_maybe_return() ) return;
  3. ...

  1. bool check_and_do_somethings_and_maybe_return() {
  2. if( some-condition ) return 1;
  3. if( some-other-condition ) { do-something; return 1; }
  4. return 0;
  5. }
etc.

This requires editing each return.

If you want to avoid that, maybe add a boolean temporary to the original code - instead of returning immediately, delay all of the returns to

  1. void foo() {
  2. bool return_early = false;
  3. if( some-condition ) return_early=true;
  4. if( !return_early ) {
  5. if( some-other-condition ) { do-something; return_early = true; }
  6. if( !return_early ) ...
  7. }
  8. if( return_early ) return;
THEN you can safely extract the method a line or statement at a time.

No comments: