Skip to content

Commit 9b135d6

Browse files
committed
Add clean is better than clever from Rob Pike GH-47
with an extension
1 parent 32b5713 commit 9b135d6

1 file changed

Lines changed: 84 additions & 0 deletions

File tree

lectures/12_clean_code.md

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,90 @@ a well-written code is easy to read, understand, debug, maintain, extend, etc.
4242
- like having a nice handwriting
4343
:::
4444

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+
func isPrime(n int) bool {
64+
if n < 2 {
65+
return false
66+
}
67+
68+
for i := 2; i*i <= n; i++ {
69+
if n%i == 0 {
70+
return false
71+
}
72+
}
73+
74+
return true
75+
}
76+
```
77+
78+
:::::::::
79+
::::::::: {.column width="50%"}
80+
```go
81+
func isPrime(n int) bool {
82+
if n < 2 {
83+
return false
84+
}
85+
86+
for i := 2; i <= n/2; i++ {
87+
if n%i == 0 {
88+
return false
89+
}
90+
}
91+
92+
return true
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+
func isPrime(n int) bool {
107+
if n < 2 {
108+
return false
109+
}
110+
111+
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
112+
if n%i == 0 {
113+
return false
114+
}
115+
}
116+
117+
return true
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}
126+
127+
:::
128+
45129
# hierarchy in style guides
46130

47131
:::::::::::: {.columns}

0 commit comments

Comments
 (0)