码迷,mamicode.com
首页 > 其他好文 > 详细

代码可读性的改良

时间:2015-06-13 14:15:45      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

首先, 有这样的代码,逻辑是没错的,但是长而且可读性不好:

message = subAction == "add" ?  String.format(format, contentMap.get("owner"), contentMap.get("ownerHomeName"))
         : String.format(format, contentMap.get("ownerHomeName"))

改良版1,代码没那么长了,但是可读性没什么改善:

message = String.format(format, contentMap.get("owner"), contentMap.get("ownerHomeName"))
message = subAction == "add" ? message : String.format(format, contentMap.get("ownerHomeName")) 

改良版2,多一行,看起来可读性就好多了

addMessage = String.format(format, contentMap.get("owner"), contentMap.get("ownerHomeName"))
removeMessage = String.format(format, contentMap.get("ownerHomeName"))
message = subAction == "add" ? addMessage : removeMessage 

朋友给的python版本解决方案,可惜他没看参数个数:

foo = lambda x: String.format( format , contentMap.get( x) )
message = foo( owner ) if subAction is add else foo( ownerHomeName )

 

代码可读性的改良

标签:

原文地址:http://www.cnblogs.com/code-style/p/4573366.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!