首先, 有这样的代码,逻辑是没错的,可是长并且可读性很差:python
message = subAction == "add" ? String.format(format, contentMap.get("owner"), contentMap.get("ownerHomeName"))
: String.format(format, contentMap.get("ownerHomeName"))
改良版1,代码没那么长了,可是可读性没什么改善:spa
message = String.format(format, contentMap.get("owner"), contentMap.get("ownerHomeName"))
message = subAction == "add" ? message : String.format(format, contentMap.get("ownerHomeName"))
改良版2,多几行,看起来可读性就好多了code
addMessage = String.format(addFormat, contentMap.get("owner"), contentMap.get("ownerHomeName")) removeMessage = String.format(removeFormat, contentMap.get("ownerHomeName")) message = subAction == "add" ? addMessage : removeMessage
朋友给的python版本解决方案,惋惜他没看参数个数:orm
foo = lambda x: String.format( format , contentMap.get( x) ) message = foo( 'owner' ) if subAction is 'add' else foo( 'ownerHomeName' )