Java 在if/else条件内调用方法是一种不好的做法吗?

Java 在if/else条件内调用方法是一种不好的做法吗?,java,if-statement,coding-style,conditional,conditional-statements,Java,If Statement,Coding Style,Conditional,Conditional Statements,这样做是否被认为是不好的做法: Scanner scan = new Scanner(System.in); if(scan.nextInt() == 5) { //testing if input is equal to 5 System.out.println("input equals 5"); } 那么: Scanner scan = new Scanner(System.in); if(scan.nextInt() == scan.nextInt

这样做是否被认为是不好的做法:

Scanner scan = new Scanner(System.in);
if(scan.nextInt() == 5) {                //testing if input is equal to 5
    System.out.println("input equals 5");
}
那么:

Scanner scan = new Scanner(System.in);
if(scan.nextInt() == scan.nextInt()) {    //testing if two inputted ints are equal to each other
    System.out.println("input1 equals input 2");
}

我在某个地方读到,这可能会导致“意想不到的结果”,但我不知道这是什么意思。我已经对此进行了很多测试,没有遇到任何意外情况。

在if/else中调用方法并不是一个坏习惯。它很好,尤其是当它返回一个只需要一次的值时。

一个意外结果的示例:

public static int count;

public static void run1() {
    count = 0;
    long r1 = getNum1();
    long r2 = getNum2(); // it is called in any case, so count = 1
    if (r1 == 1L && r2 == 0L) { /* if r1 = 1 and r2 = 0 then print "blah"
                                   if r1 = 0 then r2 is not checked! (lazy evaluation) */
        System.out.println("blah");
    }
    System.out.println(count); // always print 1 (count = 1)
}

public static void run2() {
    count = 0;
    if (getNum1() == 1L && getNum2() == 0L) { /* if getNum1() = 1 and getNum2() = 0 then print "blah"
                                                 if getNum1() = 0 then getNum2() is not checked, so count = 0! */
        System.out.println("blah");
    }
    System.out.println(count); // depends on the getNum1() result
}

// return 0 or 1 depending on milliseconds of the current time is even or odd
public static long getNum1() {
    return System.currentTimeMillis() % 2L;
}

// same as getNum1() and addition set count to 1
public static long getNum2() {
    count = 1;
    return System.currentTimeMillis() % 2L;
}

这里的问题不是在
if
块的条件内调用方法。问题是您的函数不是纯粹的,即它有副作用。如果你看一下@Krayo的例子,你会发现两个看似等价的代码段如何具有不同的行为:
&
只执行第二个表达式,如果第一个表达式的计算结果为
true
。类似地,
|
仅执行第二个表达式,如果第一个表达式为
false

看看原理。它指出您的方法应该计算并返回一个值,或者它们应该更改对象的状态,但不能同时更改这两个状态


编辑:另外,看看原理。程序的语义不应取决于是通过存储还是通过计算获得值。如果您的程序在访问字段时的行为与执行计算相同值的方法时的行为不同,那么您可能应该修复您的方法注意:行为和性能是两双鞋:访问字段比计算值快

你在哪里读到的?不,不是。也许你误解了你读到的内容。@Keppil我记不太清楚了,但它在互联网上的某个地方,所以它的可靠性值得怀疑。如果这些方法不是“纯”的,这可能会导致意外的结果。例如,如果您决定添加另一个测试以检查
扫描仪.nextInt()==7
,则该测试将从
扫描仪
读取另一个值。例如,在使用
迭代器时,这是一个非常常见的错误。所以,如果你知道你想做什么,那没关系,但是如果你忘了…@Alboz谢谢,现在我想起来了,我在一个随机的网站上读到了这篇文章,它的可靠性可能不是很好。对不起,我不完全理解这段代码中发生了什么(我是Java的初学者)。你能解释一下代码的作用以及它是如何导致意外结果的吗?我用一些注释对其进行了扩展。哦,我看到了潜在的问题,非常感谢!