Can you store a variable inside a if-clause?

后端 未结 6 1582
不思量自难忘°
不思量自难忘° 2021-01-01 16:21

I\'m kinda waiting for a \'no\' answer on this question.

I was interested if you can save a variable at the same time when you checking it in an if-clause.

相关标签:
6条回答
  • 2021-01-01 16:35

    From the department "My Programming Language is Better Than Your Programming Language": In Groovy, you can use the "?." operator:

    Bar bar = foo?.bar
    if (bar != null) {
    }
    

    In Java, this is good pattern(*):

    Bar bar = foo == null ? null : foo.getBar();
    if (bar != null) {
    }
    

    *: Something you can save in your fingertips.

    0 讨论(0)
  • 2021-01-01 16:41

    if you want to limit the scope of Bar bar I'd add { and } around the code that Michael posted.

    void foo()
    {
        // some code ...
    
        // this block limits the scope of "Bar bar" so that the rest of the method cannot see 
        // it.
        {
            Bar bar;
            if(foo!=null && (bar = foo.getBar())!=null){
                System.out.println("Success: " + bar);
            } else {
                System.out.println("Failiure.");
            }
        }
    }
    

    You might also want to check into the null object pattern if it makes sense. I personally try to avoid things being null if I can... really think about if you want null to be allowed or not.

    0 讨论(0)
  • 2021-01-01 16:42

    Actually I think that is a way to do this using Java Optional, here's an example:

    Optional.ofNullable("text").ifPresent( $0 -> {
      System.out.println($0.toUpperCase());
    });
    

    Or in your case:

      if(foo != null){
          Optional.ofNullable(foo.getBar()).ifPresent(bar -> {
              System.out.println("Success: " + bar);
          });
      }
    
    0 讨论(0)
  • 2021-01-01 16:48

    This is the closest you can get:

    Bar bar;
    if(foo!=null && (bar = foo.getBar())!=null){
      System.out.println("Success: " + bar);
    } else {
      System.out.println("Failiure.");
    }
    
    0 讨论(0)
  • 2021-01-01 16:51

    Three points that completely fail to answer the question:

    null is evil. Don't write methods that return it. Your example problem would then disappear.

    I think you might be missing out on encapsulation. Instead of foo.getBar() could the interface of foo be made such that you perform a "tell don't ask" operation?

    Side-effects in expression tends to cause bad code. Prefer more, simpler lines to fewer, buggy lines. The usual exception if using ++ to increment an index when accessing a buffer, or similar iterator style algorithms.

    0 讨论(0)
  • 2021-01-01 16:53

    I have used that technique when iterating over lines from a BufferedReader:

    BufferedReader br = // create reader
    String line
    while ((line = br.readLine()) != null) {
        // process the line
    }
    

    So yes, you can do an assignment, and the result off that will be the left hand side variable, which you can then check. However, it's not legal to declare variables inside a test, as they would then only be scoped to that expression.

    0 讨论(0)
提交回复
热议问题