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

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

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

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

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 :-)

转载于:https://my.oschina.net/cevin15/blog/615841

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值