Untitled
unknown
java
a year ago
2.3 kB
22
Indexable
public class OrderService {
private final Database database;
public OrderService(Database database) {
this.database = database;
}
public void placeOrder(String customerId, String productId, int quantity) {
try {
validateOrderDetails(customerId, productId, quantity);
Customer customer = findCustomerById(customerId);
Product product = findProductById(productId);
checkProductAvailability(product, quantity);
createAndSaveOrder(customer, product, quantity);
updateProductStock(product, quantity);
System.out.println("Order placed successfully");
} catch (OrderException e) {
System.out.println(e.getMessage());
}
}
private void validateOrderDetails(String customerId, String productId, int quantity) throws OrderException {
if (customerId == null || productId == null || quantity <= 0) {
throw new OrderException("Invalid order details");
}
}
private Customer findCustomerById(String customerId) throws OrderException {
Customer customer = database.findCustomerById(customerId);
if (customer == null) {
throw new OrderException("Customer not found");
}
return customer;
}
private Product findProductById(String productId) throws OrderException {
Product product = database.findProductById(productId);
if (product == null) {
throw new OrderException("Product not found");
}
return product;
}
private void checkProductAvailability(Product product, int quantity) throws OrderException {
if (product.getStock() < quantity) {
throw new OrderException("Product not available");
}
}
private void createAndSaveOrder(Customer customer, Product product, int quantity) {
Order order = new Order(customer, product, quantity);
database.saveOrder(order);
}
private void updateProductStock(Product product, int quantity) {
product.setStock(product.getStock() - quantity);
database.updateProduct(product);
}
}
class OrderException extends Exception {
public OrderException(String message) {
super(message);
}
}Editor is loading...
Leave a Comment