Object-oriented programming · interview question
In a class representing an e-commerce order, you want to ensure that the quantity of items is never negative. Which approach should you take to enforce this invariant?
Multiple choiceHardchapter-3-curatedpremiumoopinvariants-and-validation
class Order {
private int quantity;
public Order(int quantity) {
if (quantity < 0) throw new IllegalArgumentException("Quantity cannot be negative");
this.quantity = quantity;
}
public void setQuantity(int quantity) {
if (quantity < 0) throw new IllegalArgumentException("Quantity cannot be negative");
this.quantity = quantity;
}
}Answer and explanation
Correct answer
D. Use a private field for quantity and validate it in the constructor and all modifying methods.
Why
Using a private field ensures that the quantity can only be accessed and modified through controlled methods. By validating in the constructor and all modifying methods, the class enforces its invariants, maintaining integrity.
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…