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

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.

主站蜘蛛池模板: 黄浦区| 清苑县| 百色市| 遵化市| 秀山| 临漳县| 西乌| 稻城县| 增城市| 七台河市| 兴安盟| 班玛县| 嵊泗县| 卢氏县| 秦皇岛市| 鸡泽县| 沙河市| 泗水县| 马龙县| 治县。| 鄂尔多斯市| 尚义县| 云梦县| 墨玉县| 遂宁市| 赣榆县| 遂宁市| 霍城县| 洪泽县| 新安县| 亚东县| 光山县| 林周县| 秀山| 临猗县| 黔东| 峡江县| 东海县| 双辽市| 丹东市| 文安县|