不好的代碼

今天在檢視代碼,發現一些問題,順便貼出來,第一篇簡書文章

濫用guard

首先看一下官方對guard關鍵字的說明

Early Exit
A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true.”
摘錄來自: Apple Inc. “The Swift Programming Language (Swift 3 beta)”。 iBooks. https://itun.es/us/k5SW7.l

而下面的例子并不是對異常情況進行判斷,所以該場景下應該使用ifswitch

guard orderData["workOrderType"].numberValue == OrderType.ServiceOrder.rawValue else {
    orderCell.orderType = .WorkOrder
    orderCell.configCell(orderData, indexPatch: indexPath)
    return orderCell
}

使用硬代碼(魔鬼數字)

cell.remarkLabel.preferredMaxLayoutWidth = (screenWidth - 320) + 304

代碼擠成一坨

下面的代碼有幾個問題

  • 代碼擠成一坨
  • 用代碼去生成按鈕(不推薦)
  • 用代碼去生成按鈕的目的實際上是想設置按鈕的顏色,這個可能通過tintColor很方便地處理
let cancelButton = UIButton(type: .System)
cancelButton.frame = CGRectMake(0, 0, 42, 20)
cancelButton.setTitle(cancelButtonTitle, forState: .Normal)
cancelButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16)
cancelButton.setTitleColor(UIColor.colorWithHexString("#29b6f6"), forState: .Normal)
picker.setCancelButton(UIBarButtonItem(customView: cancelButton))
let doneButton = UIButton(type: .System)
doneButton.frame = CGRectMake(0, 0, 50, 20)
doneButton.setTitle(doneButtonTitle, forState: .Normal)
doneButton.titleLabel?.font = UIFont.boldSystemFontOfSize(16)
doneButton.setTitleColor(UIColor.colorWithHexString("#29b6f6"), forState: .Normal)
picker.setDoneButton(UIBarButtonItem(customView: doneButton))

比較好的代碼應該這樣(忽略selector的處理)

let cancelButton = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: nil)
cancelButton.tintColor = UIColor.colorWithHexString("#29b6f6")
picker.setCancelButton(cancelButton)

let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: nil)
doneButton.tintColor = UIColor.colorWithHexString("#29b6f6")
picker.setDoneButton(doneButton)

類型初始化有誤

下面代碼中的變量不可能為浮點型,卻聲明為浮點型

var currentPage = 1.0
var pageSize = 10.0

毫無意義的重載

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
}

Bean使用復數

Bean是抽象的,不應該為復數
public static class WorkOrdersBean

多層if嵌套

圖片來自網絡
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容