【发布时间】:2021-04-23 08:06:11
【问题描述】:
我有一个问题,即在使用多个在其逻辑中使用相同对象的 if 语句时如何最好地对代码进行排序。
我正在自定义表中的列值,根据 columnId,将应用不同的逻辑来提取该特定列的值。
鉴于我有三个不同的列,分别命名为“Column 1”、“Column 2”和“Column 3”,其中“Column 1”和“Column 3”在其逻辑中都使用了一个名为 obj 的自定义对象,而“Column 2”没有。
对 if 语句进行排序的最佳方法是什么?我应该在哪里创建我的对象?我添加了三种不同的情况,哪一种最好,为什么?另一个更好的独奏?
提前致谢!
// Case 1
public Object getColumnValue(String columndId) {
if (columndId.equals("Column 1") || columndId.equals("Column 3")) {
customObject obj = new customObject();
if (columndId.equals("Column 1")) {
// do something with the custom object
} else if (columndId.equals("Column 3") ||) {
// do something else with the custom object
}
} else if (columndId.equals("Column 2")) {
// do something without the custom object
} else {
return null;
}
}
// Case 2
public Object getColumnValue(String columndId) {
customObject obj = new customObject();
if (columndId.equals("Column 1") {
// do something with the custom object
} else if (columndId.equals("Column 2")) {
// // do something without the custom object
} else if (columndId.equals("Column 3")) {
/// do something with the custom object
} else {
return null;
}
}
// Case 3
public Object getColumnValue(String columndId) {
if (columndId.equals("Column 1") {
customObject obj = new customObject();
// do something with the custom object
} else if (columndId.equals("Column 2")) {
// // do something without the custom object
} else if (columndId.equals("Column 3")) {
customObject obj = new customObject();
/// do something with the custom object
} else {
return null;
}
}
// Case 4
public Object getColumnValue(String columndId) {
switch (columnId) {
case "Column 1":
case "Column 3":
customObject obj = new customObject();
switch (columnId) {
case "Column 1":
// do somethingt with custom object
case "Column 3":
// do something else with custom object
}
case "Column 2":
// do something without custom object
}
}
【问题讨论】:
-
你听说过 switch-case 语句吗?无论哪种方式,这都是一个代码审查问题
-
@Stultuske 代码审查网站不会接受它,代码是假设的,永远不会顺利。
-
@Stultuske 是的,我有,所以你是说在创建对象之前先列出应该使用对象的多个情况,然后呢?每种情况都旨在以不同的方式处理对象。就像我刚刚添加的案例 4。
-
@MarcusNystad 避免 if/else(或多个 if)涉及审查拥有方法
getColumnValue()的类的设计。设计模式策略可以帮助替换多个 if。` 对于案例 4,您可以在私有方法中提取第二个switch以避免switch嵌套 -
@Cedric 不幸的是,我无法更改拥有
getColumnValue()方法的类,因为它是我不允许更改的软件代码库的一部分。鉴于此,我应该如何考虑何时创建对象以及如何以最佳方式嵌套类似的 if?
标签: java if-statement design-patterns logic