Refactoring: Variable interdependencies

I’m working on a legacy project with catastrophically bad code. Two small examples are variable names like ‘ttt’, ‘iii’ and so on, and using such variables for multiple purposes. This makes it very hard to trace data dependencies and understand what are actual dependencies.

In one instance I found code similar to the following

if (function1(&variable)) {
    function2(&variable);
}

The ‘variable’ is obviously an “in/out argument” but it is not obvious if it actually transfers information from ‘ function1’ to ‘function2’. This seems to indicate a tight connection between the two functions.

If there are tests that cover this, one simple way to make that connection obvious, is to separate the ‘variable’ into two.

if (function1(&variable1)) {
    function2(&variable2);
}

This will immediately make it evident if the out-data from ‘function1’ is used in the second call. It will, of course, not guarantee that there is no context in which it would, but if your tests fails, then you have a case when it really did.

Refactoring is often dependent on your knowledge about the code, this is one small trick to learn more about it.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.