Be $#%!ing explicit# Programming - 葵花宝典
d*n
1 楼
Example
Consider fetching a user id from a cookie. How much language knowledge do
you need to answer the following questions given the implementation?
What happens if the cookie is not present?
What happens if the cookie value is not a well formatted number?
What happens if the cookie value is a negative number?
Scala
import play.api.mvc.RequestHeader
def getUserId()(implicit request: RequestHeader) = {
request.cookies.get("uid").map(_.value.toLong).filter(_ > 0)
}
Go
import (
"fmt"
"http"
"strconv"
)
func getUserId(r *http.Request) (int64, error) {
c, err := r.Cookie("uid")
if err != nil {
return 0, err
}
i, err := strconv.ParseInt(c.Value, 10, 64)
if err != nil {
return 0, err
}
if i <= 0 {
return 0, fmt.Errorf("invalid user id")
}
return i, nil
}
In this particular case, the Scala code is clearly shorter and perhaps more
eloquent, but the point that I am trying to illustrate in general is that
the Go code is explicit and the Scala code requires context to understand.
Be $#%!ing explicit
In my experience, explicit code has a lot of benefits.
Explicit code is easier for novices and for non-authors to grok.
Explicit code is easier to edit with small changes.
Explicit code makes the error cases obvious.
Explicit code makes the test cases obvious.
Explicit code is easier to debug (try setting a breakpoint in the Scala code
above).
https://www.quora.com/Scala-vs-Go-Could-people-help-compare-contrast-these-
on-relative-merits-demerits
Consider fetching a user id from a cookie. How much language knowledge do
you need to answer the following questions given the implementation?
What happens if the cookie is not present?
What happens if the cookie value is not a well formatted number?
What happens if the cookie value is a negative number?
Scala
import play.api.mvc.RequestHeader
def getUserId()(implicit request: RequestHeader) = {
request.cookies.get("uid").map(_.value.toLong).filter(_ > 0)
}
Go
import (
"fmt"
"http"
"strconv"
)
func getUserId(r *http.Request) (int64, error) {
c, err := r.Cookie("uid")
if err != nil {
return 0, err
}
i, err := strconv.ParseInt(c.Value, 10, 64)
if err != nil {
return 0, err
}
if i <= 0 {
return 0, fmt.Errorf("invalid user id")
}
return i, nil
}
In this particular case, the Scala code is clearly shorter and perhaps more
eloquent, but the point that I am trying to illustrate in general is that
the Go code is explicit and the Scala code requires context to understand.
Be $#%!ing explicit
In my experience, explicit code has a lot of benefits.
Explicit code is easier for novices and for non-authors to grok.
Explicit code is easier to edit with small changes.
Explicit code makes the error cases obvious.
Explicit code makes the test cases obvious.
Explicit code is easier to debug (try setting a breakpoint in the Scala code
above).
https://www.quora.com/Scala-vs-Go-Could-people-help-compare-contrast-these-
on-relative-merits-demerits