O Ternary Operator
Spoken language is informal and therefore sometimes verbose:
“If Harold is on a diet, serve him a bowl of berries, otherwise give him a piece of pie.”
You see this informal verbosity in code as well:
if (onDiet) {
serveDessert(Dessert.BERRIES);
} else {
serveDessert(Dessert.PIE);
}
But code should be neither informal, nor verbose. If performing one action, code should appear to be performing one action. The Ternary Operator can help:
serveDessert(onDiet ? Dessert.BERRIES : Dessert.PIE);
Used skillfully, the Ternary Operator keeps your code laconic, yet still perfectly clear:
“If Harold’s on a diet, give him berries, otherwise pie.”