java - 同时链接多个方法调用?提供的示例
问题描述
简而言之,我有一个if
具有多种不同结果的语句,但有很多共同的代码。
我想确保以下代码是做我想做的事情的正确方法
(例如:链接方法调用,如图所示)..这是正确的吗?
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
}
所以- 这是解决这个问题的正确方法吗?
我可以链接方法调用(如图所示)并让它们同时触发吗?
如果不是,那么有效执行此操作的正确方法是什么?
反馈非常感谢!谢谢。
解决方案
您可以使用内部的if
块switch
:
if (notifType != null) {
switch(notifType) {
case NOTIFICATION_TYPE_SOUND_AND_VIBRATION:
....
break;
case NOTIFIATION_TYPE_VIBRATION_ONLY:
....
break;
case NOTIFIATION_TYPE_SILENT_REMINDER:
....
}
}
您还可以使用多个 if 语句而不是 switch。use 可以使代码更高效的唯一方法是使用if (notifType != null)
一次。
推荐阅读
- javascript - 无头 JS 后台任务未在 React-Native 中运行
- api - 哪个 Sabre API 可以获取航班上预订的乘客数量?
- javascript - 运行良好,但突然显示错误。例外:一天内服务调用次数过多:urlfetch
- regex - 正则表达式捕获中间网址
- angular - 如何将@angular/fire 添加到 Nx 工作区(Angular 项目)?
- c# - C# 最佳实践 (LINQ) 检查字符串列表/数组中的字符串
- digital-ocean - 数字海滴
- javascript - 如何将excel文件(exceljs)上传到s3
- flutter - 使用 Flutter with IOS 接收共享文件意图
- javascript - 分页逻辑 - Vue