代碼可讀性的改良

首先, 有這樣的代碼,邏輯是沒錯的,可是長並且可讀性很差: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' )
相關文章
相關標籤/搜索