Start learning free

LESSON 73 OF 338 · CONDITIONAL STATEMENTS

Code Quality: Redundant Else Statements

Lesson Read the full explanation

We will learn a simple trick to improve our code quality: removing redundant else statements.

Video Lesson:

STEP 1 OF 1
    Ctrl + Enter to check

    GO · CONDITIONAL STATEMENTS

    Redundant Else Statement in Go, explained

    Introduction

    In this lesson, we will explore a simple yet effective technique to enhance code quality by removing redundant else statements. This practice not only makes your code cleaner but also easier to read and maintain. Understanding and applying this technique is crucial for writing efficient and professional code.

    Redundant else statements often appear in conditional logic where the else block is unnecessary. By eliminating these, we can streamline our code and avoid potential pitfalls.

    Understanding the Basics

    Before diving into the main concepts, let's understand the basics of conditional statements. In programming, conditional statements allow us to execute different code blocks based on certain conditions. The most common conditional statements are if, else if, and else.

    Here is a simple example:

    if condition {
        // code block A
    } else {
        // code block B
    }
    

    In this structure, if the condition is true, code block A is executed; otherwise, code block B is executed.

    Main Concepts

    Redundant else statements occur when the else block is not necessary. This usually happens when the if block contains a return statement, making the else block redundant. Let's see an example:

    func checkNumber(num int) string {
        if num > 0 {
            return "Positive"
        } else {
            return "Non-positive"
        }
    }
    

    In the above code, the else block is redundant because the if block already returns a value. We can refactor this code to improve its quality:

    func checkNumber(num int) string {
        if num > 0 {
            return "Positive"
        }
        return "Non-positive"
    }
    

    By removing the else block, the code becomes cleaner and easier to read.

    Examples and Use Cases

    Let's look at more examples to understand how removing redundant else statements can improve code quality:

    func getDiscount(price float64) float64 {
        if price > 100 {
            return price * 0.1
        } else {
            return 0
        }
    }
    

    Refactored version:

    func getDiscount(price float64) float64 {
        if price > 100 {
            return price * 0.1
        }
        return 0
    }
    

    Another example:

    func isEven(num int) bool {
        if num%2 == 0 {
            return true
        } else {
            return false
        }
    }
    

    Refactored version:

    func isEven(num int) bool {
        if num%2 == 0 {
            return true
        }
        return false
    }
    

    Common Pitfalls and Best Practices

    When refactoring code to remove redundant else statements, be cautious of the following common pitfalls:

    • Ensure that the refactored code maintains the same logic and functionality.
    • Avoid introducing new bugs by thoroughly testing the refactored code.

    Best practices include:

    • Always review your code for redundant else statements during code reviews.
    • Write clear and concise comments to explain the logic, especially after refactoring.

    Advanced Techniques

    In more complex scenarios, you might encounter nested conditional statements. The same principle of removing redundant else statements applies. Consider the following example:

    func categorizeAge(age int) string {
        if age < 13 {
            return "Child"
        } else {
            if age < 20 {
                return "Teenager"
            } else {
                return "Adult"
            }
        }
    }
    

    Refactored version:

    func categorizeAge(age int) string {
        if age < 13 {
            return "Child"
        }
        if age < 20 {
            return "Teenager"
        }
        return "Adult"
    }
    

    Code Implementation

    Here is a complete example demonstrating the correct use of removing redundant else statements:

    package main
    
    import "fmt"
    
    // checkNumber returns whether a number is positive or non-positive
    func checkNumber(num int) string {
        if num > 0 {
            return "Positive"
        }
        return "Non-positive"
    }
    
    // getDiscount calculates the discount based on the price
    func getDiscount(price float64) float64 {
        if price > 100 {
            return price * 0.1
        }
        return 0
    }
    
    // isEven checks if a number is even
    func isEven(num int) bool {
        if num%2 == 0 {
            return true
        }
        return false
    }
    
    // categorizeAge categorizes age into Child, Teenager, or Adult
    func categorizeAge(age int) string {
        if age < 13 {
            return "Child"
        }
        if age < 20 {
            return "Teenager"
        }
        return "Adult"
    }
    
    func main() {
        fmt.Println(checkNumber(10))    // Output: Positive
        fmt.Println(getDiscount(150.0)) // Output: 15
        fmt.Println(isEven(4))          // Output: true
        fmt.Println(categorizeAge(18))  // Output: Teenager
    }
    

    Debugging and Testing

    When debugging code related to conditional statements, consider the following tips:

    • Use print statements or a debugger to trace the flow of execution.
    • Write unit tests to verify the correctness of each function.

    Example test cases:

    package main
    
    import "testing"
    
    func TestCheckNumber(t *testing.T) {
        if checkNumber(10) != "Positive" {
            t.Error("Expected Positive for input 10")
        }
        if checkNumber(-5) != "Non-positive" {
            t.Error("Expected Non-positive for input -5")
        }
    }
    
    func TestGetDiscount(t *testing.T) {
        if getDiscount(150.0) != 15 {
            t.Error("Expected 15 for input 150.0")
        }
        if getDiscount(50.0) != 0 {
            t.Error("Expected 0 for input 50.0")
        }
    }
    
    func TestIsEven(t *testing.T) {
        if !isEven(4) {
            t.Error("Expected true for input 4")
        }
        if isEven(5) {
            t.Error("Expected false for input 5")
        }
    }
    
    func TestCategorizeAge(t *testing.T) {
        if categorizeAge(10) != "Child" {
            t.Error("Expected Child for input 10")
        }
        if categorizeAge(18) != "Teenager" {
            t.Error("Expected Teenager for input 18")
        }
        if categorizeAge(25) != "Adult" {
            t.Error("Expected Adult for input 25")
        }
    }
    

    Thinking and Problem-Solving Tips

    When approaching problems related to conditional statements, consider the following strategies:

    • Break down complex conditions into simpler, manageable parts.
    • Use flowcharts or pseudocode to visualize the logic before coding.
    • Practice refactoring code to remove redundant else statements in various scenarios.

    Conclusion

    In this lesson, we covered the importance of removing redundant else statements to improve code quality. By understanding and applying this technique, you can write cleaner, more efficient, and maintainable code. Remember to practice and review your code regularly to identify and eliminate redundant else statements.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free