mardi 22 août 2017

Is it a good practice to use ? : (conditional operator) in Java - pros cons

Recently I've inherited a code base where the Java conditional operator ? : to be the norm and it is used all across the code base.

In general in my coding style do not use them that much for simplicity in debugging. I can see conditional operators can improve readability. But was curious to know if there any other pros or cons in using conditional operators.

boolean haveId = complexIdLogic(...);
// buy methods such as buyBeer() or buyPop() return count of units bought.

difference:

int drinksCount = haveId ? buyBeer() : buyPop();

vs

int drinksCount = 0;
if (haveId){
    drinksCount = buyBeer();
else 
    drinksCount = buyPop();

Aucun commentaire:

Enregistrer un commentaire