您的位置:首页 > 编程语言

新手编程入门一:用Exception来进行流程控制

2016-02-17 09:25 246 查看
摘要: 减少if else,减少嵌套,让代码更好查阅!

在我们平时工作时,写到最多的代码其实是业务代码。而由于业务的复杂性,代码中经常会有各种逻辑判断参杂其中。

还是熟悉的博客系统,还是“发表博文”这个业务。

在编程刚入门时,业务代码可能是这么写的。

public static long newBlog(String title, String content, long userId) throws Exception{
User user = User.ME.loadById(userId);
long id = 0;
if(user==null){
return -1;
}else if(User.isFobbiden()){
return -1;
}else{
try{
if(StringUtils.isBlank(title)){
return -1;
}
if(StringUtils.isBlank(content)){
return -1;
}
id = Blog.ME.save(title, content, user.getId());

List<User> friends = User.ME.myFriends(user.getId());
UserService.noticeUsers(friends);   //通知用户朋友有更新
}catch(Exception e){
e.printStackTrace();
}
}

return id;
}

Servlet这么调用。

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//TODO: 从Req中获取title,content,userId
long id = BlogService.newBlog(title, content, userId);
if(id<=0){
resp.getWriter().print("发表博文失败");
}else{
resp.getWriter().print("发表博文成功");
}

}

这里有个很明显的弊端,就是用户发表博文失败,不知道为何失败!那我们再修改下业务代码,给出详细的失败原因。

public static Map<String, Object> newBlog(String title, String content, long userId) throws Exception{
User user = User.ME.loadById(userId);
Map<String, Object> resultMap = new HashMap<String, Object>();
long id = 0;
if(user==null){
resultMap.put("result", false);
resultMap.put("msg", "用户不存在");
return resultMap;
}else if(User.isFobbiden()){
resultMap.put("result", false);
resultMap.put("msg", "用户已被禁止");
return resultMap;
}else{
try{
if(StringUtils.isBlank(title)){
resultMap.put("result", false);
resultMap.put("msg", "博客标题不能为空");
return resultMap;
}
if(StringUtils.isBlank(content)){
resultMap.put("result", false);
resultMap.put("msg", "博客内容不能为空");
return resultMap;
}
id = Blog.ME.save(title, content, user.getId());

List<User> friends = User.ME.myFriends(user.getId());
UserService.noticeUsers(friends);   //通知用户朋友有更新
resultMap.put("result", true);
return resultMap;
}catch(Exception e){
e.printStackTrace();
resultMap.put("result", false);
resultMap.put("msg", e.getMessage());
return resultMap;
}
}
}

Servlet这么调用。

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//TODO: 从Req中获取title,content,userId
Map<String, Object> resultMap = newBlog(title, content, userId);
if(!(boolean)resultMap.get("result")){
resp.getWriter().print(resultMap.get("msg"));
}else{
resp.getWriter().print("发表博文成功");
}

}

现在用户发表博文失败后,也能清楚地得到失败的原因进行修改了。但是,newBlog方法这乱七八糟的重复代码岂是我们这些“洁癖”程序员能忍的?

主角是时候登场了:Exception。其实流程控制不止if else,continue,break,return等等。主动抛出异常用熟了也是各种爽快!

上代码。

public static long newBlog(String title, String content, long userId) throws Exception{
User user = User.ME.loadById(userId);
if(user==null){
throw new Exception("用户不存在");
}
if(User.isFobbiden()){
throw new Exception("用户已被禁止");
}
long id = 0;
try{

if(StringUtils.isBlank(title)){
throw new Exception("博客标题不能为空");
}
if(StringUtils.isBlank(content)){
throw new Exception("博客内容不能为空");
}
id = Blog.ME.save(title, content, user.getId());

List<User> friends = User.ME.myFriends(user.getId());
UserService.noticeUsers(friends);   //通知用户朋友有更新
}catch(Exception e){
throw new Exception(e.getMessage());
}

return id;
}

可以看到,在上面这个方法中,我们主动把失败原因封装成一个新的异常抛出,来中断了我们业务的操作。这时的Servlet是这么写的。

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//TODO: 从Req中获取title,content,userId
try{
newBlog(title, content, userId);
resp.getWriter().print("发表博文成功");
}catch(Exception e){
resp.getWriter().print(e.getMessage());
}

}

怎么样,对比起第二种写法是不是貌似优雅了一些?

一些浅见,希望对你平常工作学习写代码有所帮助。当然,最重要的是学会举一反三。Enjoy it :-)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息