重构实例1:消除冗余代码
先描述一下场景:
我们的web项目提供了若干个基于HTTP协议的POST接口,用于给第三方的用户写入数据,为了验证写入数据者的身份,这样的接口肯定会要求对方传递身份标识,接口得到标识以后会验证写入者的标识,正确就执行请求,错误就返回失败信息,由于是基于同样的检测身份的机制,每个接口都做了同样的事情,体现在代码里就有大量的冗余代码,如果要消除冗余代码,我可以把冗余代码写成一个函数,在每一个接口里调用,这样的话,也会有大量重复的调用语句,感觉还是不完美,于是思考之后还是借助OO来做这个事情,需要说明的是,我们的语言是python,web项目采用的框架是webpy
重构之前的代码
class Apply: def POST(self): try: wi = web.input() token = wi.token projectId = wi.projectId serverToken = getServerToken(db,token) if serverToken == None: return '{"result":"error","message":"token is error"}' if checkExpires(serverToken): return '{"result":"error","message":"token is expires"}' userId = serverToken.userId result = create.joinProject(userId,int(projectId)) if result[0] == True: return '{"result":"ok","message":"ok"}' else: return '{"result":"error","message":"%s"}' %(result[1]) except: if DEBUG: raise return '{"result":"error","message":""}' class AddFolder: def POST(self): try: wi = web.input() token = wi.token serverToken = getServerToken(db,token) if serverToken == None: return '{"result":"error","message":"token is error"}' if checkExpires(serverToken): return '{"result":"error","message":"token is expires"}' userId = serverToken.userId folderName = wi.folderName pFolderId = int(wi.pFolderId) if hasattr(wi,"pFolderId") else 0 projectId = util.unhash17(int(wi.projectId)) if hasattr(wi,"projectId") else 0 folderId,deep,msg = tn.newFolder(db,folderName,userId,pFolderId,0,projectId) if folderId > 0: return '{"result":"ok","message":"%s","folderId":"%s","deep":"%s"}' %(msg,folderId,deep) else: return '{"result":"error","message":"%s","folderId":"%s","deep":"%s"}' %(msg,folderId,deep) except: if DEBUG: raise return '{"result":"error","message":""}'
我从代码里挑了两个API来展现代码冗余的情况,这两个API里做了很多一样的事情,例如使用用户传过来的token(身份标识)去系统查询(getServerToken调用)一旦不匹配告诉用户token is error,然后继续检查token是否超时,最后,整个代码是包含在try-catch块中,一旦有意外的事情(例如BUG)发生,需要返回错误信息给用户,只有每个API中间一块的处理代码是不一样的,这还是两个API,实际上整个功能模块至少有十几个API,而且还会继续增加,那么这种情况下,API越多则冗余代码越多,并且一旦需要修改就很痛苦,例如,每个catch块原来就是return出错误信息,结果后来要求给模块增加调试状态,在打开调试的时候返回异常信息用于调试,上线时异常时则只能返回规矩的JSON字符串给用户
重构以后
class OpenApiBase: def __init__(self): self.funPOST = self.POST self.POST = self.post def post(self): try: wi = web.input() token = wi.token self.serverToken = getServerToken(db,token) web.debug(str(self.serverToken)) if self.serverToken == False: return '{"result":"error","message":"token is error"}' if checkExpires(self.serverToken): return '{"result":"error","message":"token is expires"}' #执行每个子类具体的代码 return self.funPOST() except: if DEBUG: raise return '{"result":"error","message":""}' class Apply(OpenApiBase):#继承OpenApiBase def POST(self): wi = web.input() projectId = wi.projectId userId = self.serverToken.userId result = create.joinProject(userId,int(projectId)) if result[0] == True: return '{"result":"ok","message":"ok"}' else: return '{"result":"error","message":"%s"}' %(result[1]) class AddFolder(OpenApiBase):#继承OpenApiBase def POST(self): wi = web.input() userId = self.serverToken.userId folderName = wi.folderName pFolderId = int(wi.pFolderId) if hasattr(wi,"pFolderId") else 0 projectId = util.unhash17(int(wi.projectId)) if hasattr(wi,"projectId") else 0 folderId,deep,msg = tn.newFolder(db,folderName,userId,pFolderId,0,projectId) if folderId > 0: return '{"result":"ok","message":"%s","folderId":"%s","deep":"%s"}' %(msg,folderId,deep) else: return '{"result":"error","message":"%s","folderId":"%s","deep":"%s"}' %(msg,folderId,deep)
重构以后,每个子类的POST函数只做自己应该处理的事情,对于身份的检测全部交给父类完成,一旦没通过身份检测,子类POST里的代码根本就不会被执行
posted on 2012-07-26 17:58 codestyle 阅读(1728) 评论(0) 编辑 收藏 举报