Prompt
Always use safe attribute access patterns to handle potentially null or undefined attributes. Instead of direct attribute access that might raise AttributeError, use getattr() with a default value. This pattern prevents null reference errors and makes code more robust.
Example:
# Unsafe:
version = obj.__version__
value = obj.as_tuple()
# Safe:
version = getattr(obj, '__version__', '')
try:
value = getattr(obj, 'as_tuple')()
except AttributeError:
value = None
This approach:
- Provides fallback values for missing attributes
- Makes null cases explicit and handled
- Reduces runtime errors from missing attributes
- Makes code more maintainable by centralizing null handling
When using this pattern, choose meaningful default values that make sense in the context rather than always defaulting to None.