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

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

Detected an if block that checks for the same condition on both branches ($X). The second condition check is useless as it is the same as the first, and therefore can be removed from the code,

Run Locally

Run in CI

Defintion

rules:
  - id: useless-if-conditional
    message: Detected an if block that checks for the same condition on both
      branches (`$X`). The second condition check is useless as it is the same
      as the first, and therefore can be removed from the code,
    languages:
      - go
    severity: WARNING
    pattern: |
      if ($X) {
          ...
      } else if ($X) {
          ...
      }
    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")

}