// bad
var d int // elapsed time in days
// good
var elapsedTimeInDays int // 全局使用
// bad
func getThem(theList [][]int) [][]int {
var list1 [][]int // list1是啥,不知道
for _, x := range theList {
if x[0] == 4 { // 4是啥,不知道
list1 = append(list1, x)
}
}
return list1
}
// good
type Cell []int // 标识[]int作用
func (cell Cell) isFlagged() bool { // 说明4的作用
return cell[0] == 4
}
func getFlaggedCells(gameBoard []Cell) []Cell { // 起有意义的变量名
var flaggedCells []Cell
for _, cell := range gameBoard {
if cell.isFlagged() {
flaggedCells = append(flaggedCells, cell)
}
}
return flaggedCells
}
// bad
// …then…and then … and then ... // 平铺直叙描述整个过程
func RenderPage(request *http.Request) map[string]interface{} {
page := map[string]interface{}{}
name := request.Form.Get("name")
page["name"] = name
urlPathName := strings.ToLower(name)
urlPathName = regexp.MustCompile(`['.]`).ReplaceAllString(
urlPathName, "")
urlPathName = regexp.MustCompile(`[^a-z0-9]+`).ReplaceAllString(
urlPathName, "-")
urlPathName = strings.Trim(urlPathName, "-")
page["url"] = "/biz/" + urlPathName
page["date_created"] = time.Now().In(time.UTC)
return page
}
// good
// 按空间分解,这样的好处是可以集中精力到关注的功能上
var page = map[string]pageItem{
"name": pageName,
"url": pageUrl,
"date_created": pageDateCreated,
}
type pageItem func(*http.Request) interface{}
func pageName(request *http.Request) interface{} { // name 相关过程
return request.Form.Get("name")
}
func pageUrl(request *http.Request) interface{} { // URL 相关过程
name := request.Form.Get("name")
urlPathName := strings.ToLower(name)
urlPathName = regexp.MustCompile(`['.]`).ReplaceAllString(
urlPathName, "")
urlPathName = regexp.MustCompile(`[^a-z0-9]+`).ReplaceAllString(
urlPathName, "-")
urlPathName = strings.Trim(urlPathName, "-")
return "/biz/" + urlPathName
}
func pageDateCreated(request *http.Request) interface{} { // Date 相关过程
return time.Now().In(time.UTC)
}
// bad
func (customer *Customer) statement() string {
totalAmount := float64(0)
frequentRenterPoints := 0
result := "Rental Record for " + customer.Name + "\n"
for _, rental := range customer.rentals {
thisAmount := float64(0)
switch rental.PriceCode {
case REGULAR:
thisAmount += 2
case New_RELEASE:
thisAmount += rental.rent * 2
case CHILDREN:
thisAmount += 1.5
}
frequentRenterPoints += 1
totalAmount += thisAmount
}
result += strconv.FormatFloat(totalAmount,'g',10,64) + "\n"
result += strconv.Itoa(frequentRenterPoints)
return result
}
// good 逻辑分解后的代码
func statement(custom *Customer) string {
bill := calcBill(custom)
statement := bill.print()
return statement
}
type RentalBill struct {
rental Rental
amount float64
}
type Bill struct {
customer *Customer
rentals []RentalBill
totalAmount float64
frequentRenterPoints int
}
func calcBill(customer *Customer) Bill {
bill := Bill{}
for _, rental := range customer.rentals {
rentalBill := RentalBill{
rental: rental,
amount: calcAmount(rental),
}
bill.frequentRenterPoints += calcFrequentRenterPoints(rental)
bill.totalAmount += rentalBill.amount
bill.rentals = append(bill.rentals, rentalBill)
}
return bill
}
func (bill Bill) print() string {
result := "Rental Record for " + bill.customer.name + "(n"
for _, rental := range bill.rentals{
result += "\t" + rental.movie.title + "\t" +
strconv.FormatFloat(rental.amount, 'g', 10, 64) + "\n"
}
result += "Amount owed is " +
strconv.FormatFloat(bill.totalAmount, 'g', 10, 64) + "\n"
result += "You earned + " +
strconv.Itoa(bill.frequentRenterPoints) + "frequent renter points"
return result
}
func calcAmount(rental Rental) float64 {
thisAmount := float64(0)
switch rental.movie.priceCode {
case REGULAR:
thisAmount += 2
if rental.daysRented > 2 {
thisAmount += (float64(rental.daysRented) - 2) * 1.5
}
case NEW_RELEASE:
thisAmount += float64(rental.daysRented) * 3
case CHILDRENS:
thisAmount += 1.5
if rental.daysRented > 3 {
thisAmount += (float64(rental.daysRented) - 3) * 1.5
}
}
return thisAmount
}
func calcFrequentRenterPoints(rental Rental) int {
frequentRenterPoints := 1
switch rental.movie.priceCode {
case NEW_RELEASE:
if rental.daysRented > 1 {
frequentRenterPointst++
}
}
return frequentRenterPoints
}
// bad
func findSphericalClosest(lat float64, lng float64, locations []Location) *Location {
var closest *Location
closestDistance := math.MaxFloat64
for _, location := range locations {
latRad := radians(lat)
lngRad := radians(lng)
lng2Rad := radians(location.Lat)
lng2Rad := radians(location.Lng)
var dist = math.Acos(math.Sin(latRad) * math.Sin(lat2Rad) +
math.Cos(latRad) * math.Cos(lat2Rad) *
math.Cos(lng2Rad - lngRad)
)
if dist < closestDistance {
closest = &location
closestDistance = dist
}
}
return closet
}
// good
type Location struct {
}
type compare func(left Location, right Location) int
func min(objects []Location, compare compare) *Location {
var min *Location
for _, object := range objects {
if min == nil {
min = &object
continue
}
if compare(object, *min) < 0 {
min = &object
}
}
return min
}
func findSphericalClosest(lat float64, lng float64, locations []Location) *Location {
isCloser := func(left Location, right Location) int {
leftDistance := rand.Int()
rightDistance := rand.Int()
if leftDistance < rightDistance {
return -1
} else {
return 0
}
}
closet := min(locations, isCloser)
return closet
}
// bad
/** the name. */
var name string
/** the version. */
var Version string
/** the info. */
var info string
// Find the Node in the given subtree, with the given name, using the given depth.
func FindNodeInSubtree(subTree *Node, name string, depth *int) *Node {
}
// Impose a reasonable limit - no human can read that much anyway
const MAX_RSS_SUBSCRIPTIONS = 1000
// Runtime is O(number_tags * average_tag_depth),
// so watch out for badly nested inputs.
func FixBrokenHTML(HTML string) string {
// ...
}
// bad
func (rng *Range) overlapsWith(other *Range) bool {
return (rng.begin >= other.begin && rng.begin < other.end) ||
(rng.end > other.begin && rng.end <= other.end) ||
(rng.begin <= other.begin && rng.end >= other.end)
}
// good
func (rng *Range) overlapsWith(other *Range) bool {
if other.end < rng.begin {
return false // they end before we begin
}
if other.begin >= rng.end {
return false // they begin after we end
}
return true // Only possibility left: they overlap
}
// bad 多层缩进的问题
func handleResult(reply *Reply, userResult int, permissionResult int) {
if userResult == SUCCESS {
if permissionResult != SUCCESS {
reply.WriteErrors("error reading permissions")
reply.Done()
return
}
reply.WriteErrors("")
} else {
reply.WriteErrors("User Result")
}
reply.Done()
}
// good
func handleResult(reply *Reply, userResult int, permissionResult int) {
defer reply.Done()
if userResult != SUCCESS {
reply.WriteErrors("User Result")
return
}
if permissionResult != SUCCESS {
reply.WriteErrors("error reading permissions")
return
}
reply.WriteErrors("")
}
// bad
type MooDriver struct {
gradient Gradient
splines []Spline
}
func (driver *MooDriver) drive(reason string) {
driver.saturateGradient()
driver.reticulateSplines()
driver.diveForMoog(reason)
}
// good
type ExplicitDriver struct {
}
// 使用上下文传递
func (driver *MooDriver) drive(reason string) {
gradient := driver.saturateGradient()
splines := driver.reticulateSplines(gradient)
driver.diveForMoog(splines, reason)
}


func (query *Query) doQuery() {
if query.sdQuery != nil {
query.sdQuery.clearResultSet()
}
// version 5.2 control
if query.sd52 {
query.sdQuery = sdLoginSession.createQuery(SDQuery.OPEN_FOR_QUERY)
} else {
query.sdQuery = sdSession.createQuery(SDQuery.OPEN_FOR_QUERY)
}
query.executeQuery()
}
// bad
type Loan struct {
start time.Time
expiry *time.Time
maturity *time.Time
rating int
}
func (loan *Loan) duration() float64 {
if loan.expiry == nil {
return float64(loan.maturity.Unix()-loan.start.Unix()) / 365 * 24 * float64(time.Hour)
} else if loan.maturity == nil {
return float64(loan.expiry.Unix()-loan.start.Unix()) / 365 * 24 * float64(time.Hour)
}
toExpiry := float64(loan.expiry.Unix() - loan.start.Unix())
fromExpiryToMaturity := float64(loan.maturity.Unix() - loan.expiry.Unix())
revolverDuration := toExpiry / 365 * 24 * float64(time.Hour)
termDuration := fromExpiryToMaturity / 365 * 24 * float64(time.Hour)
return revolverDuration + termDuration
}
func (loan *Loan) unusedPercentage() float64 {
if loan.expiry != nil && loan.maturity != nil {
if loan.rating > 4 {
return 0.95
} else {
return 0.50
}
} else if loan.maturity != nil {
return 1
} else if loan.expiry != nil {
if loan.rating > 4 {
return 0.75
} else {
return 0.25
}
}
panic("invalid loan")
}
// good
type LoanApplication struct {
expiry *time.Time
maturity *time.Time
}
type CapitalStrategy interface {
duration() float64
unusedPercentage() float64
}
func createLoanStrategy(loanApplication LoanApplication) CapitalStrategy {
if loanApplication.expiry != nil && loanApplication.maturity != nil {
return createRCTL(loanApplication)
}
if loanApplication.expiry != nil {
return createRevolver(loanApplication)
}
if loanApplication.maturity != nil {
return createTermLoan
}
panic("invalid loan application")
}
// bad 两个I/O写到一起了
func sendToPlatforms() {
httpSend("bloomberg", func(err error) {
if err == nil {
increaseCounter("bloomberg_sent", func(err error) {
if err != nil {
log("failed to record counter", err)
}
})
} else {
log("failed to send to bloom berg", err)
}
})
ftpSend("reuters", func(err error) {
if err == DIRECTORY_NOT_FOUND {
httpSend("reuterHelp", err)
}
})
}
//good 协程写法
func sendToPlatforms() {
go sendToBloomberg()
go sendToReuters()
}
func sendToBloomberg() {
err := httpSend("bloomberg")
if err != nil {
log("failed to send to bloom berg", err)
return
}
err := increaseCounter("bloomberg_sent")
if err != nil {
log("failed to record counter", err)
}
}
func sendToReuters() {
err := ftpSend("reuters")
if err == nil {
httpSend("reutersHelp", err)
}
}
// bad
func buyProduct(req *http.Request) error {
err := checkAuth(req)
if err != nil {
return err
}
// ...
}
func sellProduct(req *http.Request) error {
err := checkAuth(req)
if err != nil {
return err
}
// ...
}
// good 装饰器写法
func init() {
buyProduct = checkAuthDecorator(buyProduct)
sellProduct = checkAuthDecorator(sellProduct)
}
func checkAuthDecorator(f func(req *http.Request) error) func(req *http.Request) error {
return func(req *http.Request) error {
err := checkAuth(req)
if err != nil {
return err
}
return f(req)
}
}
var buyProduct = func(req *http.Request) error {
// ...
}
var sellProduct = func(req *http.Request) error {
// ...
}


void sendMessage(const Message &msg) const {...}

def sendMessage(msg):
for _, book := range books {
book.getPublisher()
}
SELECT * FROM Pubisher WHERE PublisherId = book.publisher_id
SELECT * FROM Pubisher WHERE PublisherId = book.publisher_id
SELECT * FROM Pubisher WHERE PublisherId = book.publisher_id
SELECT * FROM Pubisher WHERE PublisherId = book.publisher_id
SELECT * FROM Pubisher WHERE PublisherId = book.publisher_id
for _, book := range books {
loadEntity("publisher", book.publisher_id)
}
-
尝试界面拆成组件
-
尝试把订单拆成多个单据,独立跟踪多个流程
-
尝试用协程而不是回调来表达concurrent i/o
-
尝试复制一份代码,而不是复用同一个Process
-
尝试显式插入: state/ adapter/ strategy/template/ visitor/ observer
-
尝试隐式插入: decorator/aop
-
提高信噪比是相对于具体目标的,提高了一个目标的信噪比,就降低了另外一个目标的信噪比

更多文章请关注《万象专栏》
转载请注明出处:https://www.wanxiangsucai.com/read/cv3887