java - Is it considered correct to omit curly braces strictly on one-liners? -


i against omitting curly braces if-else-statements , see why should avoided.

however right i've come accross interesting use case, example code here:

public <e extends runtimeexception> void throwonfail(final boolean result, final supplier<e> exceptionsupplier) throws e {     objects.requirenonnull(exceptionsupplier);     if (result) return;     throw exceptionsupplier.get(); } 

i think code is:

  • as concise can get, show other variants below.
  • not vulnerable issue adding line change logic of code.

i set personal rule myself only use on control-flow statements.
practically means, return, break , continue.

two alternative versions of code shown below.

alternative 1

public <e extends runtimeexception> void throwonfail(final boolean result, final supplier<e> exceptionsupplier) throws e {     objects.requirenonnull(exceptionsupplier);     if (result) {         return;     }     throw exceptionsupplier.get(); } 

alternative 2

public <e extends runtimeexception> void throwonfail(final boolean result, final supplier<e> exceptionsupplier) throws e {     objects.requirenonnull(exceptionsupplier);     if (!result) {         throw exceptionsupplier.get();     } } 

i both make code more complicated no appereant reason.

is considered correct omit curly braces strictly on one-liners?

well there isn't hard rule on it. considering usability case, i'd use curly bracket. makes code more readable , junior developer it's easy understand. again it's purely personal/company(code-standard) choice.

and again in alternatives, i'd go alternative2

public <e extends runtimeexception> void throwonfail(final boolean result, final supplier<e> exceptionsupplier) throws e {     objects.requirenonnull(exceptionsupplier);     if (!result) {         throw exceptionsupplier.get();     } } 

why?

  1. more concise
  2. less number of lines
  3. logically straight forward

Comments

Popular posts from this blog

javascript - How to name a jQuery function to make a browser's back button work? -

python - Django-easy-pdf: xhtml2pdf reporting reportlab 2.2+ is required, but 3.0 installed -

collision detection - C++ library for mesh to mesh intersection: what is available? -