Table of Contents

Writing clean code is essential for maintaining and scaling software projects. Clean code is easier to read, understand, and modify. A critical aspect of clean code is using meaningful and descriptive names for variables, functions, and constants. Let’s explore this through some practical examples.

Constants and Variables

Constants should always be at the top of the file and named in all caps:

const MAX_SLEEP_TIME_IN_SECONDS = 10

Variables should have meaningful names that clearly indicate their purpose. Avoid using single-character names that require extra comments for clarification:

// Bad: 
d := 10 // elapsed time in days
fmt.Println(d)

// Good:
elapsedTimeInDays := 10
fileAgeInDays := 2
fmt.Println(elapsedTimeInDays)
fmt.Println(fileAgeInDays)

Naming Conventions

Using clear and descriptive names helps in understanding the code without additional comments. Let’s look at an example of counting odd and even numbers:

// Bad:
theList := getThem()
f := 0
g := 0

for _, b := range theList {
    if b%2 == 0 {
        f++
        continue
    }
    g++
}

// Good:
allNumbers := getAllNumbers()
evenNumbers := 0
oddNumbers := 0

for _, number := range allNumbers {
    if number%2 == 0 {
        evenNumbers++
    } else {
        oddNumbers++
    }
}

Avoiding Disinformation

Disinformation in code refers to using misleading or unclear naming conventions. It’s important to name functions and variables in a way that describes their purpose:

// Bad:
x := 10
y := 20
process(x, y)

// Good:
addTwoNumbers(x, y)

Making Meaningful Differences

Avoid using arbitrary differences in variable names just to satisfy the compiler. Instead, use meaningful differences:

// Bad:
p1 := Person{Name: "Sushant"}
p2 := Person{Name: "John"}

// Good:
sushant := Person{Name: "Sushant"}
john := Person{Name: "John"}

Pronounceable Names

Using pronounceable names makes it easier to discuss code in meetings and understand it:

// Bad:
var genymdhms int64

// Good:
var generationTimestamp int64

Searchable Names

Variables should be named so that they can be easily found using search:

// Bad:
time.Sleep(10)

// Good:
time.Sleep(MAX_SLEEP_TIME_IN_SECONDS)

Conclusion

Using meaningful and descriptive names in your code enhances readability and maintainability. It reduces the cognitive load on developers and makes it easier to understand the codebase. By following these principles, you can write cleaner and more efficient code.

Categorized in:

Tutorials,