我正在为我的 android 设备构建一个 HTTP 服务器。
我使用了很多 IF-ELSE 语句来处理不同的请求。
由于我将与其他人共享我的代码供以后使用,因此我必须使其尽可能清晰易读。现在,我什至无法轻松阅读我的代码。
我认为问题出在一个类中使用了很多 IF-ELSE 语句。 例如。
if(purpose.equals("readProfile"){
.....
}
else if(purpose.equals("writeProfile"){
.....
}
....
我尝试将它们分类并根据它们的类别对条件进行排序。但是可读性并没有得到很大改善。 然后我尝试在每个条件之前写简短的评论。但这让情况变得更加困惑。
如何提高条件语句的易读性?
最佳答案
作为Luiggi Mendoza说明,这是 a previous question 的跟进...
如果您使用的是 Java 7,您可以使用 switch-case statement for strings
//month is a String
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
//partsleft out for sake of brevity ..
default:
monthNumber = 0;
break;
}
(摘自上面引用的 Oracle Java 教程。)
重构
但是,这个巨大的 if-else 只是问题的一部分。由于这似乎是一个随着时间的推移而增长的结构,我建议进行彻底的重构,并使用在我看来是 Strategy pattern 的结构。 .你应该:
制定一个涵盖所有用例边界的接口(interface):
interface MyStrategy {
void execute(MyInputContext input, MyOutputContext output);
}
(对 MyInputContext 和 MyOutputContext 使用 void 方法只是一种方法,这只是一个示例,但是要处理有响应的请求,这是有道理的,就像 Servlet 的工作方式一样)
将大 IF-ELSE 语句的内容重构为该接口(interface)的实例(这些将是策略):
//VERY simplified...
class ReadProfileStrategy implements MyStrategy {
void execute(MyInputContext input, MyOutputContext output) {
//do the stuff that was in the if-else block in the "readProfile" part
}
}
//... at the branching part:
MyInputContext input; //build this here
MyOutputContext output; //build this here
switch (purpose) {
case "readProfile":
// no need to always instantiate this, it should be stateless...
new ReadProfileStrategy().execute();
break;
//... left out for sake of brevity
}
重构步骤2
如果这样做,您可以将字符串 ID 添加到接口(interface)和实例本身,并完全摆脱 if-else 或 switch 语句,您甚至可以创建一个通过 IOC 容器填充的 Map(例如) ,是最新的,并且完全灵活。
class ReadProfileStrategy implements MyStrategy {
String getID() {
return "readProfile";
}
void execute(MyInputContext input, MyOutputContext output) {
//do the stuff that was in the if-else block in the "readProfile" part
}
}
在处理请求时的类中
private final Map<String, MyStrategy> strategyMap; //fill the map using your favorite approach, like using Spring application context, using the getCode() to provide the key of the map
在处理逻辑上:
MyStrategy strategy = strategyMap.get(purpose);
if(strategy!=null) {
strategy.execute();
}
else {
//handle error here
}
关于java - 提高条件语句的易读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18759042/