Ad

Chaining Multiple Method Calls At The Same Time? Example Provided

Simply put, I have an if statement with multiple different outcomes, but a lot of code in common.
I want to make sure that the following Code is the proper way to do what I'm trying to do
(ex: chaining Method calls, as shown).. is this correct?

SharedPreferences getPrefs =
    PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

final String notifType = getPrefs.getString
    (PREF_NOTIFICATION_TYPE, NOTIFICATION_TYPE_SOUND_AND_VIBRATION);

if (notifType != null && notifType.equals
    (NOTIFICATION_TYPE_SOUND_AND_VIBRATION)) {
        // Call the appropriate Methods, depending on the Preference..
        notificationVibration();
        playNotificationTone();
        showReminderNotification();

} else if (notifType !=null && notifType.equals
    (NOTIFIATION_TYPE_VIBRATION_ONLY)) {
        // Calling alot of the same code, but minus the Sound..
        notificationVibration();
        showReminderNotification();

} else if (notifType !=null && notifType.equals
    (NOTIFIATION_TYPE_SILENT_REMINDER)) {
        // Again re-using common code..
        showReminderNotification(); 
}

public void notificationVibration() {
    // Vibration code here
}

public void playNotificationTone() {
    // Sound code here
}

public void showReminderNotification() {
    // Notification code here
}

SO - is this the correct way to go about this?
Can I chain Method calls (as shown) and have them all fire at the same time?
If not, what is the correct way to efficiently execute this?
Feedback greatly appreciated! Thanks.

Ad

Answer

You can use a if block with switch inside:

if (notifType != null) {
    switch(notifType) {
        case NOTIFICATION_TYPE_SOUND_AND_VIBRATION:
            ....
        break;
        case NOTIFIATION_TYPE_VIBRATION_ONLY:
            ....
        break;
        case NOTIFIATION_TYPE_SILENT_REMINDER:
            ....
    }
}

You can also use multiple if statements instead of switch. The only way use can make the code more efficient is by using if (notifType != null) once.

Ad
source: stackoverflow.com
Ad