- 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.
推薦閱讀
- Oracle從新手到高手
- 摩登創客:與智能手機和平板電腦共舞
- Java游戲服務器架構實戰
- Getting Started with SQL Server 2012 Cube Development
- Teaching with Google Classroom
- Android應用案例開發大全(第二版)
- OpenCV 4計算機視覺項目實戰(原書第2版)
- D3.js By Example
- App Inventor創意趣味編程進階
- 運維前線:一線運維專家的運維方法、技巧與實踐
- App Inventor少兒趣味編程動手做
- Practical GIS
- Learning D
- Mastering Drupal 8
- Mapping with ArcGIS Pro