You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: lectures/12_clean_code.md
+84Lines changed: 84 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -42,6 +42,90 @@ a well-written code is easy to read, understand, debug, maintain, extend, etc.
42
42
- like having a nice handwriting
43
43
:::
44
44
45
+
## clear is better than clever
46
+
47
+
::: {.wide-quote}
48
+
> In any kind of programming, clarity should always be the primary goal.
49
+
>
50
+
> Writing code that is straightforward and understandable is more valuable than trying to craft overly clever or intricate solutions.
51
+
>
52
+
> -- [Go Proverbs](https://go-proverbs.github.io/) by Rob Pike
53
+
54
+
:::
55
+
56
+
source: [Rob Pike’s Go Proverbs](https://golangprojectstructure.com/rob-pike-go-proverbs-3/#clear-is-better-than-clever)
57
+
58
+
## prime check -- clever vs. clear
59
+
60
+
:::::::::::: {.columns}
61
+
::::::::: {.column width="50%"}
62
+
```go
63
+
funcisPrime(nint) bool {
64
+
if n < 2 {
65
+
returnfalse
66
+
}
67
+
68
+
fori:=2; i*i <= n; i++ {
69
+
if n%i == 0 {
70
+
returnfalse
71
+
}
72
+
}
73
+
74
+
returntrue
75
+
}
76
+
```
77
+
78
+
:::::::::
79
+
::::::::: {.column width="50%"}
80
+
```go
81
+
funcisPrime(nint) bool {
82
+
if n < 2 {
83
+
returnfalse
84
+
}
85
+
86
+
fori:=2; i <= n/2; i++ {
87
+
if n%i == 0 {
88
+
returnfalse
89
+
}
90
+
}
91
+
92
+
returntrue
93
+
}
94
+
```
95
+
96
+
less efficient, but it may be easier for a reader to understand
97
+
98
+
:::::::::
99
+
::::::::::::
100
+
101
+
source: [Rob Pike’s Go Proverbs](https://golangprojectstructure.com/rob-pike-go-proverbs-3/#clear-is-better-than-clever)
102
+
103
+
##
104
+
105
+
```go
106
+
funcisPrime(nint) bool {
107
+
if n < 2 {
108
+
returnfalse
109
+
}
110
+
111
+
fori:=2; i <= int(math.Sqrt(float64(n))); i++ {
112
+
if n%i == 0 {
113
+
returnfalse
114
+
}
115
+
}
116
+
117
+
returntrue
118
+
}
119
+
```
120
+
121
+
::: {.text-smaller}
122
+
- iterating only up to the square root of n because if n has any divisor greater than its square root, there must also be a corresponding divisor smaller than the square root
123
+
- it is easier to understand than the "clever one", but less wasteful then the "clear one"
124
+
- why is the clever on better?
125
+
-[because multiplication is more efficient for the CPU than calculating the square root]{.fragment}
0 commit comments