0 day streak
java / beginner
Snippet

Conditional Order Routing Logic in a Spring Service

This snippet illustrates branching control flow inside a Spring service class. It uses an if-statement to reject invalid input amounts early and a switch expression to route processing logic based on the payment method string.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Service
public class OrderService {
public String processPayment(String paymentType, double amount) {
if (amount <= 0) {
return "Invalid amount";
}
return switch (paymentType.toUpperCase()) {
case "CREDIT_CARD" -> "Charged " + amount + " to credit card";
case "PAYPAL" -> "Redirecting " + amount + " to PayPal";
default -> "Unsupported payment method: " + paymentType;
};
}
}
spring
Breakdown
1
if (amount <= 0) {
Validates the boundary condition to stop execution when an invalid amount is provided.
2
return switch (paymentType.toUpperCase()) {
Branches into distinct execution paths based on the normalized payment type.