CS FundamentalsVery hardProduct-company design interview
This code illustrates the 'fragile base class' problem. What does it print?
This code illustrates the 'fragile base class' problem. What does it print?
class Bag:
def __init__(self): self.items = []
def add(self, x): self.items.append(x)
def add_all(self, xs):
for x in xs: self.add(x)
class CountingBag(Bag):
def __init__(self):
super().__init__(); self.count = 0
def add(self, x):
self.count += 1; super().add(x)
def add_all(self, xs):
self.count += len(xs); super().add_all(xs)
b = CountingBag()
b.add_all([1, 2, 3])
b.add(4)
print(b.count, len(b.items))- A. 4 4
- B. 7 4
- C. 7 7
- D. 3 4
Correct answer: B. 7 4
add_all adds 3 to count, then the base add_all calls self.add, which is the overridden add, adding 1 per item: 6, plus 1 for add(4) = 7. The subclass depends on a hidden implementation detail of the base, which is why composition is often safer.
Practise more Software Engineering, Git and Cloud Basics questionsSoftware Engineering, Git and Cloud Basics: notes and key points
More Software Engineering, Git and Cloud Basics questions
- What does this code print? python from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): ... def…
- Under design by contract, a method sqrt(x) has the precondition x ≥ 0. A caller passes -4 and the method fails. Whose bug is it, and which…
- A service catches every exception in a broad try/except, logs nothing and returns an empty list, so a database outage looks like 'no…
- How many of these defend against SQL injection in a login query: (1) parameterised queries / prepared statements, (2) escaping quotes by…
- A document-editor framework defines an abstract Application class with a method newDocument() that calls createDocument(); each concrete…
- An object adapter and a class adapter both make class Legacy fit interface Target. Which statement is correct?