Harden function with guards + logging for defensive programming
Purpose: Harden functions with defensive guards and debug logging
Identify:
Example invocation:
/harden process_videos
With file flag:
/harden fetch_channel_videos --file=metadata_backfill_api.py
Place guards immediately after function signature, before any logic:
def process_videos(videos, estimated_total):
# Parameter validation
assert videos is not None, "videos cannot be None"
assert isinstance(videos, list), f"videos must be list, got {type(videos)}"
assert estimated_total > 0, f"estimated_total must be positive, got {estimated_total}"
# Function logic continues...
Guard types:
debug_log(f"process_videos: videos_count={len(videos)}, estimated_total={estimated_total}")
if not videos:
debug_log(f"process_videos: empty_videos - returning")
return []
for video in videos:
debug_log(f"process_videos: processing video_id={video.get('video_id')}")
Log at:
Wrap assertions with logging for better debugging:
# Parameter validation with logging
if videos is None:
debug_log(f"process_videos: guard_failure - videos is None")
assert False, "videos cannot be None"
if not isinstance(videos, list):
debug_log(f"process_videos: guard_failure - wrong_type videos={type(videos)}")
assert False, f"videos must be list, got {type(videos)}"
After hardening, run quick complexity check:
radon cc <file> -a -s
After hardening, the system will suggest:
/debug - Full debug workflow if issues persistAfter hardening: