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?
- more concise
- less number of lines
- logically straight forward
Comments
Post a Comment