Using ternary operator with 4 expressions
java, null, ternary-operator, variables
Solution
Use of the ?: operator should be confined to make code more readable. A classic example:
a = sprintf( "There are %i green bottle%s on the wall.", i, (i==1?"":"s") );
In this case the code would be less readable if you broke it up into about 5 if/else lines.
I generally put brackets around the entire operator so that when reading it I mentally parse it as a single value.
messageColor = (color != null ? color : messageColor);
Another variant is
messageColor = color || messageColor;
Which in some languages will evaluate to "color, unless color evaluates to "false", in which case value of messageColor. In my opinion this should be avoided as it may confuse people.
The most important thing is to be consistent so the next person reading your code (even if it's you) has minimum cognitive overhead.
Problem
Is this an acceptable coding practice? ``` public class MessageFormat { private static final Color DEFAULT_COLOR = Color.RED; private Color messageColor = DEFAULT_COLOR; public MessageFormat(Person person) { Color color = person.getPreferredColor(); messageColor = (color != null) ? color : messageColor; // this line } } ``` or am I better off going with the classic ... ``` if (color != null) { messageColor = color; } ```