Identical statements in the if else body

Go pattern

Identical statements found in both the if and else bodies of an if-statement. This results in the same code execution regardless of the if-expression outcome. To optimize, eliminate the if statement entirely.


Apply with the Grit CLI
grit apply useless_if_else_body

Detected identical statements in the else if

BEFORE
package main

import "fmt"

func main() {
	var y = 1

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

	// useless-if-conditional
	if (y) {
		fmt.Println("same condition")
	} else if (y) {
		fmt.Println("same condition")
	}

}
AFTER
package main

import "fmt"

func main() {
	var y = 1

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

	// useless-if-conditional
	if (y) {
    fmt.Println("same condition")
}

}

Detected identical statements in the if else

BEFORE
package main

import "fmt"

func main() {
	var y = 1

	// useless-if-body
	if (y) {
		fmt.Println("of course")
	} else {
		fmt.Println("of course")
	}
}
AFTER
package main

import "fmt"

func main() {
	var y = 1

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

Detected identical statements in the different if else

GO
package main

import "fmt"

func main() {
	var y = 1

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