When is it appropriate to use blank final variables?

前端 未结 9 1421
野趣味
野趣味 2020-12-16 00:24

I was looking at another question about final variables and noticed that you can declare final variables without initializing them (a blank final variable). Is there a reaso

9条回答
  •  忘掉有多难
    2020-12-16 01:09

    Use a blank final variable inside a method to show that all code paths which use the variable assign that variable exactly once (or throw an exception). Java compilers will guarantee that a blank final variable is assigned before it is used.

    Example code inside some method:

      final Foo foo;
      if (condition1()) {
        foo = makeFoo(1);
      } else if (condition2()) {
        throw new BarException();
      } else {
        foo = makeFoo(-1);
      }
      ...
      blahBlahBlah(foo);
    

    Using blank final variables tells the next reader of the code that the compiler guarantees that someone assigned foo before calling blahBlahBlah(foo).

    The question asks about "blank final variables". Discussion of "blank final fields" is a different discussion, and interesting in its own right.

提交回复
热议问题