- 필수 기능
- 시작하기
- Glossary
- 표준 속성
- Guides
- Agent
- 통합
- 개방형텔레메트리
- 개발자
- API
- Datadog Mobile App
- CoScreen
- Cloudcraft
- 앱 내
- 서비스 관리
- 인프라스트럭처
- 애플리케이션 성능
- APM
- Continuous Profiler
- 스팬 시각화
- 데이터 스트림 모니터링
- 데이터 작업 모니터링
- 디지털 경험
- 소프트웨어 제공
- 보안
- AI Observability
- 로그 관리
- 관리
ID: go-best-practices/simplify-boolean-expression
Language: Go
Severity: Info
Category: Best Practices
In Go, it is considered unnecessary and less readable to write a conditional statement that returns true
or false
explicitly based on a condition. Instead, it is recommended to directly return the condition itself. Here’s why:
return condition
directly conveys the intent of the code more clearly and reduces unnecessary verbosity. It is easier for other developers to understand your code at a glance without having to analyze additional conditional statements.true
or false
based on a condition introduces redundancy in the code. Since the condition itself already evaluates to a boolean value (true
or false
), there is no need to include additional return true
or return false
statements.return condition
approach is more maintainable and flexible for future code changes. If the condition or the desired return value changes, it is easier to modify a single line rather than multiple lines of code. This minimizes the chances of introducing errors or inconsistencies during refactoring.Therefore, it is recommended to simply use return condition
instead of if condition { return true } return false
. By doing so, you improve code readability, reduce redundancy, and ensure better maintainability of your Go code.
func main() {
if foo == 1 {
return true
}
return false
}
func main() {
if foo == 1 {
return true
} else {
return false
}
}
func main() {
exists, err := h.deduper.KeyExists(ctx, dedupeKey)
if err != nil {
return false, commonhandler.RetryErrHandleResp(err)
} else if exists {
return true, commonhandler.SuccessHandleResp
}
return false, commonhandler.SuccessHandleResp
}
func main() {
if foo == 1 {
println("foo")
return true
} else {
return false
}
if strings.TrimSpace(rawMessage.Custom.Git.RepositoryURL) == "" {
return false, ""
}
return true, ""
}