functiongiveItem(itemId, amount, srcUserUid, destUserUid, needSync) end
functionMap:addNeedFood2user(uid) local count = 0 for _, city inpairs(self._cities) do if exp1 then count = count + 1end end
local needFood = self:baseFood() * 0.8 + count ^ 2 *0.12 call2User(uid, "addFood", needFood) end
functionMap:isNeedExpand() local count = 0 for _, city inpairs(self._cities) do if exp1 then count = count + 1end end if count > 400then returntrue else returnfalse end end
我们可以看到,这一个逻辑是都有用到的。
1 2 3 4
local count = 0 for _, city inpairs(self._cities) do if exp1 then count = count + 1end end
functionMap:fetchCityNum() local count = 0 for _, city inpairs(self._cities) do if exp1 then count = count + 1end end return count end
functionMap:addNeedFood2user(uid) local count = self:fetchCityNum() local needFood = self:baseFood() * 0.8 + count ^ 2 *0.12 call2User(uid, "addFood", needFood) end
functionMap:isNeedExpand() local count = self:fetchCityNum() if count > 400then returntrue else returnfalse end end
我们再举一个例子。
如果多个相同函数执行,但是由于参数长短问题,使得代码整体,有的换行,有的太短,参差不齐。
我直接使用《The Art of Readable Code》的示例:
1 2 3 4 5 6 7 8 9 10 11 12
DatabaseConnection database_connection; string error; assert(ExpandFullName(database_connection, "Doug Adams", &error) == "Mr. Douglas Adams"); assert(error == ""); assert(ExpandFullName(database_connection, " Jake Brown ", &error) == "Mr. Jacob Brown III"); assert(error == ""); assert(ExpandFullName(database_connection, "No Such Guy", &error) == ""); assert(error == "no match found"); assert(ExpandFullName(database_connection, "John", &error) == ""); assert(error == "more than one result");
所以可以多封装一层函数,将代码规整。
1 2 3 4 5 6 7 8 9
voidCheckFullName(string partial_name, string expected_full_name, string expected_error){ // database_connection is now a class member string error; string full_name = ExpandFullName(database_connection, partial_name, &error); assert(error == expected_error); assert(full_name == expected_full_name); }
这样先前繁杂代码可以变成如下清爽的代码。
1 2 3 4
CheckFullName("Doug Adams", "Mr. Douglas Adams", ""); CheckFullName(" Jake Brown ", "Mr. Jake Brown III", ""); CheckFullName("No Such Guy", "", "no match found"); CheckFullName("John", "", "more than one result");
CheckFullName("Doug Adams" , "Mr. Douglas Adams" , ""); CheckFullName(" Jake Brown ", "Mr. Jake Brown III" , ""); CheckFullName("No Such Guy" , "" , "no match found"); CheckFullName("John" , "" , "more than one result");