Reputation: 2079
I am trying to implement this logic, I was just wondering if there is a better way?
if(condition1) {
do1();
}
else if(condition2) {//especially here that I have to check condition3 here and also in the last else if
do2();
if(condition3) {
do3();
}
}
else if(condition3) {
do3();
}
Upvotes: 1
Views: 113
Reputation: 53829
When it comes to logical comparisons, usually the best rule to apply is to make the code the most readable possible regarding the conditions. Don't try to be too smart making the future reader wonder about what the code is trying to achieve.
Write your code so it is understandable and not the shortest regarding comparisons.
According to your conditions, the solutions you wrote might be the most understandable one. If it is, you should keep it as it is and not make it actually more complicated.
Upvotes: 2
Reputation: 1597
In your logic, I don't see how you can make improvements. Maybe another, clearer way to write it would be to put the condition2
and condition3
in the same else
block, since condition2
and condition3
are not mutually exclusive, like they are with condition1
:
if(condition1) {
do1();
}
else {
if(condition2) {
do2();
}
if(condition3) {
do3();
}
}
Upvotes: 2
Reputation: 8473
Try this
if(condition1)
{
do1();
}
else
{
if(condition2)
{
do2();
}
if(condition3)
{
do3();
}
}
Upvotes: 5
Reputation: 26340
if(condition1) {
do1();
}
else {
if(condition2) {
do2();
}
if(condition3) {
do3();
}
}
Upvotes: 2