go.lang.maintainability.useless-ifelse.useless-if-body

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
87,650
Download Count*

Detected identical statements in the if body and the else body of an if-statement. This will lead to the same code being executed no matter what the if-expression evaluates to. Instead, remove the if statement.

Run Locally

Run in CI

Defintion

rules:
  - id: useless-if-body
    pattern: |
      if ($X) {
          $S
      } else {
          $S
      }
    message: Detected identical statements in the if body and the else body of an
      if-statement. This will lead to the same code being executed no matter
      what the if-expression evaluates to. Instead, remove the if statement.
    languages:
      - go
    severity: WARNING
    metadata:
      category: maintainability
      technology:
        - go
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

useless-ifelse.go

package main

import "fmt"

func main() {
	fmt.Println("hello world")
	var y = 1

	if y {
		fmt.Println("of course")
	}

	// ruleid:useless-if-conditional
	if y {
		fmt.Println("of course")
	} else if y {
		fmt.Println("of course other thing")
	}

	// ruleid:useless-if-body
	if y {
		fmt.Println("of course")
	} else {
		fmt.Println("of course")
	}

	fmt.Println("of course2")
	fmt.Println(1)
	fmt.Println(2)
	fmt.Println(3)
	fmt.Println("of course2")

}