Bird
0
0

Identify the error in this Null Object pattern implementation:

medium📝 Analysis Q6 of 15
LLD - Behavioral Design Patterns — Part 2
Identify the error in this Null Object pattern implementation:
class NullCache {
  get(key) { return null; }
  set(key, value) { /* do nothing */ }
}
function fetchData(cache, key) {
  const data = cache.get(key);
  if (data) {
    return data;
  } else {
    return 'default';
  }
}
const cache = new NullCache();
console.log(fetchData(cache, 'item'));
AThe set method should throw an error.
BThe fetchData function should not check for data.
CThe get method returns null causing the if condition to fail.
DThe NullCache class should not have a set method.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze get method return

    It returns null, which is falsy in the if condition.
  2. Step 2: Effect on fetchData

    Since data is null, the else branch runs returning 'default'. This may be unexpected if Null Object should provide safe data.
  3. Final Answer:

    The get method returns null causing the if condition to fail. -> Option C
  4. Quick Check:

    Null Object should avoid returning null [OK]
Quick Trick: Null Object methods should not return null [OK]
Common Mistakes:
MISTAKES
  • Returning null instead of safe default
  • Expecting set to throw errors
  • Ignoring null checks in client code

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes