| Version 3 (modified by , 4 months ago) ( diff ) |
|---|
Purpose of NullMediaItem
The NullMediaItem class represents the absence of media (image, audio, or video) in a way that avoids special-case handling elsewhere in the code.
It follows the Null Object Pattern , which provides a default behavior for "no object" cases, eliminating the need for repetitive if media is not None or if media: checks in templates or logic.
Why use it?
Without NullMediaItem:
if question.media: for m in question.media: if m.type == "image": ...
With NullMediaItem:
for m in question.media: html += m.to_html()
→ no conditional logic needed – every MediaItem, even the null variant, understands how to behave.
Behavior of NullMediaItem
| Method | Behavior |
|---|---|
| type() | Returns "none" |
| to_dict() | Returns empty {} or None |
| to_html() | Returns "" (empty string) |
When is it used?
You can attach one or more NullMediaItem()s to a Question instead of using None, [], or omitting the field entirely.
For example:
question = TextQuestion( qid="q1", text="What is your name?", media=[NullMediaItem()] )
This way, the rendering pipeline stays uniform, regardless of whether media is present or not.
Benefits
- Simplifies templates and rendering logic
- Eliminates null checks in UI code
- Makes polymorphism clean and consistent
- Encourages Tell, Don't Ask design (don’t ask “do you have media?”, just tell media to render itself)
