Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if vs. if/else statement?

I have this kind of code in a class :

if (reload == 0) {
    String mailSuccess = "send success mail";
} else {
    String mailOther = "send other mail";
} 

if (fileError1Exists == true) {
    String mailError1 = "send mail for error 1";
}

if (fileError2Exists == true ) {
    String mailError2 = "send mail for error 2";
}

if (fileError3Exists == true ) {
    String mailError3 = "send mail for error 3";
}

And maybe because I am still green with Java, i was wondering if this kind of syntax was clean ? Every time, i saw a "if/ese" expression, it was more like this :

if (condition == 0) {
    String mailSuccess = "send success mail";
} else if (fileError1Exists == true) {
    String mailError1 = "send mail for error 1";
} else if (fileError2Exists == true) {
    String mailError2 = "send mail for error 1";
} else if (fileError3Exists == true) {
    String mailError3 = "send mail for error 1";
} else {
    String mailOther = "send other mail";
} 

Is keeping those if statements one after another like this clean ? Obviously the first sample of code works because it is already in production. But do the 1st sample and the 2nd sample code do the same thing ? Normally, it does, right ? Or am I missing something because of my lack of experience ?

Thanks in advance for your feedback. I couldn't find my awnser on previous posts.

edit thank you all for your anwsers. It helped me understand the code, and moreover, it helped me learn something new !

like image 699
SDJ Avatar asked Mar 20 '26 16:03

SDJ


1 Answers

This is a matter of requirements given. The first code will send an email for each error found, that means if all 3 errors are found, it will send 3 emails.

Your second code will send one email for the first code found and not for additional ones.

In case you want an email for every single error, take the first code. Otherwise, if you just need one email for the first error that occurs, take the second code.

EDIT To take the suggestion by @Lino into account, you could do something like

if (reload == 0) {
    String mailSuccess = "send success mail";
} else {
    String mailOther = "send other mail";
}

StringBuilder mailErrors = new StringBuilder();

if (fileError1Exists) {
    mailErrors.append("error 1 occurred");
}

if (fileError2Exists) {
    mailErrors.append("error 2 occurred");
}

if (fileError3Exists) {
    mailErrors.append("error 3 occurred");
}

String mailErrorText = mailErrors.toString();

to track errors and send one email with information about all the errors that occurred.

IMHO tracking every error is best practice.

like image 152
deHaar Avatar answered Mar 23 '26 05:03

deHaar