- Hands-On Dependency Injection in Go
- Corey Scott
- 179字
- 2021-06-10 19:17:50
Start with simple – get complicated only when you must
As programmers, we should always strive to keep things simple, and resort to complexity when there is no other way. Let's see this principle in action. Try to determine what this next example does in three seconds or less:
func NotSoSimple(ID int64, name string, age int, registered bool) string {
out := &bytes.Buffer{}
out.WriteString(strconv.FormatInt(ID, 10))
out.WriteString("-")
out.WriteString(strings.Replace(name, " ", "_", -1))
out.WriteString("-")
out.WriteString(strconv.Itoa(age))
out.WriteString("-")
out.WriteString(strconv.FormatBool(registered))
return out.String()
}
How about this one:
func Simpler(ID int64, name string, age int, registered bool) string {
nameWithNoSpaces := strings.Replace(name, " ", "_", -1)
return fmt.Sprintf("%d-%s-%d-%t", ID, nameWithNoSpaces, age, registered)
}
Applying the approach embodied in the first code to an entire system will almost certainly make it run faster, but not only did it likely take longer to code, but it's also harder to read and therefore maintain and extend.
There will be times when you need to extract extreme performance from your code, but it's far better to wait until it cannot be avoided before burdening yourself with the extra complexity.
推薦閱讀
- 數(shù)據(jù)科學(xué)實(shí)戰(zhàn)手冊(cè)(R+Python)
- C語言程序設(shè)計(jì)案例教程(第2版)
- Silverlight魔幻銀燈
- SEO實(shí)戰(zhàn)密碼
- Java軟件開發(fā)基礎(chǔ)
- Visual C
- 手把手教你學(xué)C語言
- 軟件工程
- TradeStation交易應(yīng)用實(shí)踐:量化方法構(gòu)建贏家策略(原書第2版)
- Java程序設(shè)計(jì):原理與范例
- Visual C#.NET程序設(shè)計(jì)
- Android程序設(shè)計(jì)基礎(chǔ)
- 機(jī)器學(xué)習(xí)與R語言實(shí)戰(zhàn)
- 從零開始學(xué)Linux編程
- Node.js區(qū)塊鏈開發(fā)