make nested conditionals one-dimensional! use early returns from a function rather than if/else chains. this is essential not only in the aspect of Go, but also in any language.
take a look at the following code snippet:
the above code adds cognitive load for someone who's reading ur code (the number of entities they need to think about is a lot, so they might be lost in ur code).
but take a look at the more idiomatic approach to the code:
it uses early returns (guard clauses) and provide a linear approach to logic trees
#tips #code
@Mi_Ra_Ch
take a look at the following code snippet:
func isValidPassword(password string) bool {
isValid := true
if len(password) < 8 {
isValid = false
} else {
if !containsUppercase(password) {
isValid = false
} else {
if !containsLowercase(password) {
isValid = false
} else {
if !containsNumber(password) {
isValid = false
}
}
}
}
return isValid
}
func containsUppercase(str string) bool {
// ... implementation ...
}
func containsLowercase(str string) bool {
// ... implementation ...
}
func containsNumber(str string) bool {
// ... implementation ...
}the above code adds cognitive load for someone who's reading ur code (the number of entities they need to think about is a lot, so they might be lost in ur code).
but take a look at the more idiomatic approach to the code:
func isValidPassword(password string) bool {
if len(password) < 8 {
return false
}
if !containsUppercase(password) {
return false
}
if !containsLowercase(password) {
return false
}
if !containsNumber(password) {
return false
}
return true
}
func containsUppercase(str string) bool {
// ... implementation ...
}
func containsLowercase(str string) bool {
// ... implementation ...
}
func containsNumber(str string) bool {
// ... implementation ...
}it uses early returns (guard clauses) and provide a linear approach to logic trees
#tips #code
@Mi_Ra_Ch