Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:go-best-practices/simplify-boolean-expression
Language: Go
Severity: Info
Category: Best Practices
Description
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:
Code simplicity and readability: Writing 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.
Avoidance of redundancy: Explicitly returning 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.
Maintainability and refactoring: The direct 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.