传递最小参数是否合适?

Jav*_*per 7 java design-patterns coding-style

假设我有一个对象Car,有五个参数,{numwheels,color,mileage,horsepower,maxSpeed}.我有一个需要其中3个值的方法.哪两个选项被认为是最佳实践?是否更好地传递封闭对象并减少参数数量,或者只是将极小数据传递给方法(例如:方法2中不会访问numwheels和color)?

  1. 选项1传递整个对象:

    void compute(Car c, Person p) {
        return c.mileage + c.horsepower + c.maxSpeed + p.age;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 选项2:仅传入方法值.

    void compute(int mileage, int horsepower, int maxSpeed, int age) {
        return mileage + horsepower + maxSpeed + age.;
    }
    
    Run Code Online (Sandbox Code Playgroud)

注意:假设由于某种原因,compute不能成为Car类的一部分.请记住这个假设.

Rav*_*yal 6

最好传递封闭的对象,因为计算中所需参数数量的任何变化都不会影响将来的方法签名.

实际上,您可以接受一种接口类型Vehicle.这允许计算上的数据相同的方法Bike,Jet等以后.

public int compute(Vehicle veh) {
    return veh.computePerformance();
}
Run Code Online (Sandbox Code Playgroud)

其中Car实现方法为

public int computePerformance() {
    return mileage + horsepower + maxSpeed;
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是编写易于扩展的代码.


Gho*_*ica 5

我建议第三种选择:向Car添加一个方法"compute".

这被称为"告诉,不要问".

请参阅http://martinfowler.com/bliki/TellDontAsk.html