- void foo() {
- if( some-condition ) return;
- if( some-other-condition ) { do-something; return; }
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()
- void foo() {
- if( check_and_do_somethings_and_maybe_return() ) return;
- ...
- bool check_and_do_somethings_and_maybe_return() {
- if( some-condition ) return 1;
- if( some-other-condition ) { do-something; return 1; }
- return 0;
- }
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
- void foo() {
- bool return_early = false;
- if( some-condition ) return_early=true;
- if( !return_early ) {
- if( some-other-condition ) { do-something; return_early = true; }
- if( !return_early ) ...
- }
- if( return_early ) return;
No comments:
Post a Comment