search

Home  >  Q&A  >  body text

java - 关于返回值的问题 ,return的次数到底到多少 ?

大家讲道理大家讲道理2892 days ago532

reply all(5)I'll reply

  • 迷茫

    迷茫2017-04-18 09:27:39

    If you are pursuing readability, write like this:

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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:27:39

    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;
    }

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:27:39

    The answer above is more optimized

    reply
    0
  • 阿神

    阿神2017-04-18 09:27:39

    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.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 09:27:39

    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;
    }

    reply
    0
  • Cancelreply