首页 > 解决方案 > Is passing an argument of a method to another method a bad practice?

问题描述

I have the following method:

public myMethod(argument1)
{
  int myVariable = myMethod2(argument1)
  ...
}

Is it bad practice to pass an argument from one method right into another one? I am aware alternatives exist, (such as I could use a static variable), but for the sake of learning and argument, say that I can't.

标签: methodsargumentsstandards

解决方案


这是一个面向对象编程可能变得有用的例子。例如,您可以定义这样的类。

class MyClass
{
    private:
       int myArgument;

    public:
       myMethod()
       {
          myvariable = myMethod2();  //now you don't need to worry 
                                       about passing in the redundant argument
       }
       myMethod2()
       {
          return myArgument*2;
       }

};

就您的示例而言,该类对于此应用程序来说可能是多余的,所以这件事是否取决于您。如果您开始意识到您在大量相关函数之间传递相同的参数,这就是将数据封装在对象中的想法变得有价值的地方(假设您使用的是支持 OOP 的语言,如 C++)。


推荐阅读