Created
August 3, 2015 17:04
-
-
Save yicone/6337a7cc7ec83c4a9567 to your computer and use it in GitHub Desktop.
演示响应结果(Response)包含正文(Body),以及正文包含返回码(code)的接口风格中,正文不应为空
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Order { | |
public int orderId; | |
} | |
public static class OrderService { | |
private static Order[] s_orders = new Order[3]; | |
public static Response findOrder(final int orderId) { | |
Response resp = new Response(); | |
try { | |
for (final Order o : s_orders) { | |
if (o.orderId == orderId) { | |
resp.body = new ResponseBody() { | |
{ | |
code = 0; | |
order = o; | |
} | |
}; | |
} | |
} | |
} catch (final Exception e) { | |
resp.body = new ResponseBody() { | |
{ | |
code = 999; | |
message = e.getMessage(); | |
} | |
}; | |
} | |
return new Response(); | |
} | |
public static class Response { | |
public ResponseBody body; | |
} | |
public static class ResponseBody { | |
public int code; | |
public String message; | |
public Order order; | |
} | |
} | |
// 除了查询订单的接口,之前提供的接口,使用时都可以沿用这个“惯例” | |
public static class OtherAllCaseConsumer { | |
public static void main() { | |
int orderId = 6666; | |
OrderService.Response findOrderResponse = OrderService.findOrder(orderId); | |
assert (findOrderResponse != null); | |
assert (findOrderResponse.body != null); | |
// 如果上述两个断言失败,显示 系统出错了 给用户, 实质是未获取到有效的响应内容 | |
if (findOrderResponse.body.code != 0) { | |
if (!TextUtils.isEmpty(findOrderResponse.body.message)) { | |
// 显示 message 给用户 | |
} else { | |
// !眼前一抹黑 | |
} | |
return; | |
} | |
// 1. 代码从语义上准确的表达了目标对象为空 | |
if (findOrderResponse.body.order == null) { | |
// 告诉用户未查询到对应订单 | |
} | |
} | |
} | |
// 使用订单查询的接口 | |
public static class ThisCaseConsumer { | |
public static void main() { | |
int orderId = 6666; | |
OrderService.Response findOrderResponse = OrderService.findOrder(orderId); | |
assert (findOrderResponse != null); | |
// 2. “惯例”不在了,用响应内容为空,代替表达目标对象为空 | |
if (findOrderResponse.body == null) { | |
// 可以认为查询操作成功,相当于 body.code == 0,告诉用户对应的订单不存在 | |
return; | |
} | |
if (findOrderResponse.body.code != 0) { | |
if (!TextUtils.isEmpty(findOrderResponse.body.message)) { | |
// 显示 message 给用户 | |
} else { | |
// !眼前一抹黑 | |
} | |
return; | |
} | |
if (findOrderResponse.body.order == null) { | |
// 3. 好像不重要了,按照人为约定,可能永远不会走到这个分支里. 但是又不放心是否要补个处理 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment