> On Jan 9, 2019, at 1:14 PM, Brian Goetz <brian.go...@oracle.com> wrote:
> 
> 
>> Still, I believe that if you really care about making the structure of the 
>> code clear, then you would be well advised to (a) avoid inverting the sense 
>> of boolean tests, and (b) avoid relying on the fact that one arm of a 
>> conditional has a control transfer so  that you can “get away with” saving a 
>> level of horizontal indentation.
> 
> I think the clarity knife sometimes cuts in this direction, but sometimes in 
> the other direction.
> 
> If I have:
> 
>     if (x instanceof P(var y)) {
>         // more than a page of code
>     }
>     else
>         throw new FooException();
> 
> vs
> 
>     if (!(x instanceof P(var y)))
>         throw new FooException();
> 
>     // the same page of code
> 
> In the latter case, i've checked all my preconditions up front, so it's more 
> obviously fail-fast.  Maintainers are less likely to forget the condition 
> they just tested a page ago, and readers are more able to build a mental 
> model of the invariants of the happy path for this method.  So I think it's 
> not always about "saving indentation"; in this case it's "get the 
> precondition checks out of the way, and set me up to do the work without 
> further interruption.”

Sure—and in such a situation I might still prefer the first form, _or_ I might 
well choose to write instead

    if (!(x instanceof P))
        throw new FooException();

    String y = ((P)x).yfield;
    // the same page of code

and forego the slight advantage of pattern matching (perhaps relying on the 
compiler’s flow analysis to notice that the cast `(P)x` does not actually 
require a redundant run-time check), in order to make the scope of `y` 
crystal-clear.

There are stylistic tradeoffs here, and no one style is perfect.  If one style 
gets too squirrelly, the programmer can choose to use another.  Therefore we 
need not always go to extremes to salvage one specific style; that’s a 
meta-tradeoff language designers can choose to make.



Reply via email to