Thursday, February 9, 2017

Safely extract a method in any C++ code

Moved here for better formatting: http://jay.bazuzi.com/Safely-extract-a-method-in-any-C++-code/

2 comments:

Arne Mertz said...

Thanks for the detailed recipe! I've written something similar but way shorter a while ago (see below). You mention setting the return type, but if what you factor out was a block in the beginning, then there is none. If it wasn't a block, then introducing the lambda (or any block) might result in compile errors when variables that are created in the new block are used after it. These together make up the return type of the lambda and the new function.



https://arne-mertz.de/2016/10/large-legacy-applications-tools/#Example_factor_out_a_function

Jay Bazuzi said...

Cool Arne.

I may be misunderstanding the concern you bring up. The recipe demands a block (or a scoping statement) to avoid the problems of changing variable scope and lifetime. But blocks can return a value. For example: https://gist.github.com/JayBazuzi/9b5b2aeb95368b10decbb4c9706a88ae

I do think there's something that needs fixing in the recipe. There are multiple cases but they are all a bit muddled today:

1. No return statements, no problem.
2. Return in a `void` method.
3. Return a value in a non-`void` method.

If there is a return, you have to make sure that all paths return, and in #2 the compiler won't help you.

Also, a previous iteration of the recipe could extract an expression, not just a block of statements, but I removed that for simplicity. We'll have to fill that in later.