Java 私有方法'return'或'set value'



我的私有方法应该返回值还是直接设置值?有这样或那样的好处吗?如果有,为什么?

这是我的代码:

public class MinorMatrix {
int[][] minorMatrix;
int determinant;
int matrixSize;
public MinorMatrix(int a, int b, int[][] matrix) {
    matrixSize = matrix.length;
    createMinorMatrix(a, b, matrix);
    createDetermiant();
}
private void createDetermiant() {
    // Do this (with return):
    return value;
    // or with void
    determinant = value;
}
}

通常,您应该返回值,这里的void样式会产生副作用。它可能稍微更有效地使用副作用,但在许多情况下(这就是其中之一),它使程序的流程更难遵循。

使用return,而不是void,因为这样任何维护人员都不必调查您的createDeterminant()方法,他们可以将其视为黑盒。如果你使用副作用,未来的用户不知道如何获得所创造的价值。找到答案的唯一方法是研究增加不必要工作量的函数。

最新更新