官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 广州市| 志丹县| 南和县| 平武县| 仙居县| 上思县| 酒泉市| 盘山县| 黄山市| 高州市| 渝中区| 策勒县| 延长县| 囊谦县| 花垣县| 上高县| 岐山县| 从江县| 武陟县| 抚远县| 壶关县| 泰州市| 鹤庆县| 开封县| 丰原市| 东莞市| 道真| 雷山县| 庆元县| 湘西| 石渠县| 滨海县| 铁岭县| 江永县| 曲靖市| 赤峰市| 中卫市| 石城县| 尼玛县| 乌拉特中旗| 辽源市|