Always validate potentially null or empty values before use, and provide explicit default values when handling optional data. This prevents runtime errors and makes code behavior more predictable.
Key practices:
Example:
// Before
func processValue(m map[string]interface{}, key string) string {
return m[key].(string)
}
// After
func processValue(m map[string]interface{}, key string) string {
if v, ok := m[key].(string); ok && v != "" {
return v
}
return "" // explicit default
}
// Even better with generics
func valueOrDefault[T any](m map[string]interface{}, key string) T {
if v, ok := m[key].(T); ok {
return v
}
return *new(T)
}
Enter the URL of a public GitHub repository