Object-oriented programming · interview question
Consider an Order class that must always have a positive quantity. How should this invariant be enforced?
Multiple choiceHardchapter-3-curatedpremiumoopinvariants-and-validation
class Order {
private int quantity;
public void setQuantity(int quantity) {
if (quantity <= 0) throw new IllegalArgumentException("Quantity must be positive");
this.quantity = quantity;
}
}Answer and explanation
Correct answer
A. Use a setter method with validation.
Why
Using a setter method with validation ensures that any changes to the quantity are checked, maintaining the positive quantity invariant.
Test yourself on Object-oriented programming
A free test with instant, explained results. No account needed.
More Object-oriented programming questions
- In a typical e-commerce application, how should a CartItem object access the price of a Product?
- What design principle is violated if a Cart class directly manipulates a Product's price?
- Why might CartItem hold a Product reference instead of copying every product field into loose variables?
- In the context of e-commerce, which class is most likely to contain a method called calculateTotalPrice()?
- What access modifier should be used for fields to adhere to encapsulation principles?
- How would you explain a key reason to use encapsulation when designing an object with multiple responsibilities in an…