This product is not supported for your selected Datadog site. ().
이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다. 현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.
Metadata
ID:go-best-practices/modify-parameter
Language: Go
Severity: Info
Category: Best Practices
Description
Assigning new values to function parameters exhibits several bad coding practices and should be avoided for several reasons:
Redefining parameters: The code redefines a parameter within the function body by assigning a new value. This is considered a bad practice because it can lead to confusion and make the code harder to understand. Modifying a function parameter in this manner breaks the expected behavior and can cause unexpected side effects. It is generally best to treat function parameters as read-only values and avoid reassigning them.
Shadowing variables: The code further exacerbates the issue by using the short variable declaration := to define a new variable within the function body. This shadows the original parameter, making it inaccessible within the function. Shadowing variables can cause confusion and make the code harder to reason about. It is better to use distinct variable names to maintain clarity and avoid any unintended side effects.
To write more maintainable and understandable code, it is advisable to adhere to the following practices:
Avoid redefining function parameters.
Use descriptive and unambiguous variable names.
Avoid shadowing variables.
Maintain consistency in variable references.
By following these best practices, the code becomes more readable and easier to manage and avoids introducing unnecessary complexity and confusion.
Non-Compliant Code Examples
funcfun1(paramint){// Shadowing 'param'param:=51}func(r*Type)fun2(paramint){param:=51}funcfun3(paramint){iftrue{// Outside of the main function body, := always shadowsparam,err:=doSomething()}}
Compliant Code Examples
funcfun1(paramint){// Assign a new value to the parameterparam=doSomething()}funcfun2(paramint){// In the main function body, := with multiple variables in the left// will reassign instead of shadowingparam,err:=doSomethingElse()}funcfun3(paramint){constfun4=func(){// Shadowing inside an inner function doesn't affect the outer functionparam:=doSomething()}}
funcfun(_int){fortrue{// We don't check _ for shadowing_,err:=doSomething()}}
func(r*Type)fun1(ctxcontext.Context){// As a special case, we allow shadowing context parametersctx:=context.WithCancel(ctx)}funcfun2(ctxcontext.Context){ctx:=context.WithCancel(ctx)}
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- go-best-practices # Rules to enforce Go best practices.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다