Search code examples
algorithmperformancelanguage-agnosticreadability

Passing the same variable through intermediate methods which don't directly process it


More than often I find myself passing a variable into a method, where it is not directly used, but is yet passed to another method for further processing. I don't know if there is a name for this practice either. I can explain it better with a sample code:

static void main() {
    int a = method1(var1, var2, var3)
}

int method1(int var1, int var2, int var3) {
    var4 = some_function_of(var1, var2)
    return method2(var3, var4)
}

int method2(int var 3, int var4) {
    return some_other_function_of(var3, var4)
}

This case can be expanded where there the same variable (var3) is passed through even longer chains of methods. I think this could be a bad practice, as in my example method1 is some sort of intermediate that is not manipulating var3. Is there a better practice for performance, design and/or readability?


Solution

  • At least for object oriented languages the answer would be:

    1. You definitely want to avoid such code - as you struggle to reduce your parameter list to the absolut minimum; the goal is zero.
    2. If you find that your class should offer various methods that all require the "same" parameter; than that makes that parameter a candidate to be a field within your class.

    In non-oo languages, I think you have to pragmatically balance between having more functions and parameter list length. In your example,

    static void main() {
      int var4 = some_function_of(var1, var2)
      int a = method2(var3, var4)
    }
    

    avoiding method1 ... saves you passing var3 to your first method. And you are still within the rules of the "single layer of abstraction" principle.