编程技巧:将对象或值作为方法参数传递

ilo*_*arn 4 java oop parameter-passing

传递参数在日常编程中很常见,但是我们应该将参数作为对象或值传递吗?

(一个)

public boolean isGreaterThanZero(Payment object) {
    if (object.getAmount() > 0) {
       return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

(B)

public boolean isGreaterThanZero(int amount) {
    if (amount > 0) {
       return true;
    }

    return false;
}
Run Code Online (Sandbox Code Playgroud)

Rev*_*nzo 8

这些都不是.

使用适当的OOP,您将在Payment对象上使用isGreaterThanZero(),即:

class Payment {
  int amount
  public boolean isGreaterThanZero() {
    return amount > 0
  }
}
Run Code Online (Sandbox Code Playgroud)

然后:

Payment payment
boolean flag = payment.isGreaterThanZero()
Run Code Online (Sandbox Code Playgroud)