0

Is it possible to have an if statement on multiple lines? I currently have an apex class with a large conditional statement and I would like to have it on multiple lines to improve readability.

7

Yes! The example below works just fine

string a;
string b;
string c;

if (a == b || 
    b == c) {
    //Do something
}
| improve this answer | |
1

Go by

Creating small meaningful functions

Answering the original question, Yes the conditions in apex can be put on multiple lines.

As the main purpose to splitting conditions on multiple lines is code readability, Going further I would suggest to create small meaningful functions, This will make your code even more readable.

Once I had developed a functionality to take backup of data, here is snippet of that code.

This is more readable than any kind of indentation.

 private Boolean isEligibleForBackup(String interval, Date lastBackupDate) {
        return (isEligibleForDailyBackup(interval, lastBackupDate)
                || isEligibleForWeeklyBackup(interval, lastBackupDate)
                || isEligibleForMonthlyBackup(interval, lastBackupDate));
    }

    private Boolean isEligibleForDailyBackup(String interval, Date lastBackupDate) {
        return (interval.equalsIgnoreCase('daily')
                && lastBackupDate.daysBetween(System.today()) >= 1);
    }

    private Boolean isEligibleForWeeklyBackup(String interval, Date lastBackupDate) {
        return (interval.equalsIgnoreCase('weekly')
                && lastBackupDate.daysBetween(System.today()) >= 7);
    }

    private Boolean isEligibleForMonthlyBackup(String interval, Date lastBackupDate) {
        return (interval.equalsIgnoreCase('monthly')
                && monthsBetween(lastBackupDate, System.today()) > 0);
    }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.