1 回答

TA貢獻2080條經驗 獲得超4個贊
在不了解更多周圍代碼的情況下,很難簡化整個事情并為您提供完成的代碼。
但是我有幾個建議給你,我認為你可以應用這些建議來簡化你自己的邏輯。
建議 #1
我在這里看到的一個問題是使邏輯更加混亂,這是int輸入變量(偏移量、限制、頁面、頭部、最后)的基本類型()的使用。
問題是您正在將輸入變量與默認值(在 Go 中稱為“零值”)進行比較,例如 0,或者defaultLimit您實際嘗試檢查的是用戶是否提供了這些輸入。
我的建議是使這些輸入變量指針 ( *int),以便您可以將它們與它們進行比較,nil以便更輕松、更清楚地檢查用戶是否發送了這些輸入。我認為這將使邏輯更具可讀性。
例如,offset & limit 你可以簡化成這樣的:
if offset != nil {
opt.SetSkip(*offset)
}
if limit != nil {
opt.SetLimit(*limit)
}
建議#2
我還建議以不同的方式處理錯誤。
首先檢查錯誤情況。如果輸入無效,則返回錯誤。
如果沒有錯誤,然后處理成功案例。這是用 Golang(以及其他語言)編寫代碼的一種非常常見的方式。
像這樣的東西:
// in the function from your post:
// check for error cases
err := checkError(offset, limit, page, head, last)
if err != nil {
return make([]bson.M, 0), err
}
// handle success (non error) cases
if offset == defaultOffset && limit != defaultLimit && page == defaultPage {
opt.SetLimit(limit)
//if just limit
} else if // ... the rest of the success cases ...
// ... elsewhere in the same file (or package) ...
func checkError(offset, limit, page, head, last int) error {
if offset != defaultOffset && limit != defaultLimit && page != defaultPage && head != 0 && last != 0{
return errors.New("can't show all queries")
//if there are all query
} else if offset != defaultOffset && limit != defaultLimit && page != defaultPage {
return errors.New("can't show all queries")
//if there are all query
} else if offset != defaultOffset && limit == defaultLimit && page != defaultPage{
return errors.New("can't merge page and offset")
//if combine page & offset
} else if head != 0 && last != 0 {
return errors.New("can't merge head and last")
//if combine head & last
} else if limit <=0 || page <= 0{
return errors.New("BSON field value must be >= 0, actual value -20")
//if limit & page value smaller than 0
}
return nil
}
- 1 回答
- 0 關注
- 112 瀏覽
添加回答
舉報