java - 关于返回值的问题 ,return的次数到底到多少 ?
大家讲道理
大家讲道理 2017-04-18 09:25:39
0
5
525
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(5)
迷茫

If you are pursuing readability, write like this:

pubilc Object get() {
    if () {
        return A;
    }

    if () {
        return B;
    }

    return C;
}
伊谢尔伦

Except for poor readability, there is no problem. A method may return different resultsaccording to different situations, but each call will only return one of the results.

A better way to write is to prioritize exception branches in the method body and return the exception result as early as possible.

pubilc Object get(){
    //第一个if对应题目中的最后一个else
    if(invalidResult1) {
        return null;
    }
    //第二个if对应题目中倒数第二个else
    if(invalidResult2) {
        return null;
    }
    //对应题目中第二个if
    return succesResult;
}
Peter_Zhu

The answer above is more optimized

阿神

One key point is that a method will only return once when called. If your method may return twice, it will not pass compilation. Because the method returns a value, it means that the method has reached the end point and the program will exit the method.

大家讲道理

I think it should be like this

pubilc Object get(){
        Object obj=null;
        if(){
            
            if(){
               obj=x;
            }else{
               obj=xx;
            }
            
        }else{
            obj=xxx;
        }
      return obj;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template