HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

"Have a safe trip"… or not, depending on four conditions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fourtripsafeconditionsdependingnothave

Problem

I have 4 booleans and all must be met to determine the value of a String:

String message = (!isNameBlank && !isDestinationBlank
    && isDestinationValid && isAmountValid)
    ? "Have a safe trip!" : "Please try again!";


If I do this, it doesn't look elegant either:

String message = "";
if(!isNameBlank && !isDestinationBlank
    && isDestinationValid && isAmountValid) {
    message = "Have a safe trip!";
} else {
    message = "Please try again!";
}


Is there a better convention when comparing many booleans in a statement?

Solution

When it comes to long and complex logic summation I recommend, as Legato says, to use one row for each condition.
I also think it is more readable if you sum all the conditions to a new variable that explains the result with a meaningful name like this:

boolean isTripPossible = 
   !isNameBlank && 
   !isDestinationBlank && 
   isDestinationValid && 
   isAmountValid;      

String message = isTripPossible ? "Have a safe trip!" : "Please try again!";

Code Snippets

boolean isTripPossible = 
   !isNameBlank && 
   !isDestinationBlank && 
   isDestinationValid && 
   isAmountValid;      

String message = isTripPossible ? "Have a safe trip!" : "Please try again!";

Context

StackExchange Code Review Q#119358, answer score: 61

Revisions (0)

No revisions yet.