Careeroza
Real World Example
Food Order Bill with Methods
Real backends split work into small methods with clear names: one calculates the subtotal, one the discount, one the taxes. Each can be tested on its own. This is how an order service at Zomato or Swiggy is organised (as classes and methods).
Example
public class Main {
static final double GST_RATE = 0.05;
static double subtotal(double[] prices, int[] qty) {
double sum = 0;
for (int i = 0; i < prices.length; i++) sum += prices[i] * qty[i];
return sum;
}
static double discount(double amount, String coupon) {
return switch (coupon) {
case "WELCOME50" -> Math.min(amount * 0.5, 100);
case "FLAT75" -> amount >= 300 ? 75 : 0;
default -> 0;
};
}
static double deliveryFee(double amount, double distanceKm) {
if (amount >= 499) return 0;
return distanceKm <= 3 ? 25 : 25 + (distanceKm - 3) * 8;
}
static double round2(double v) {
return Math.round(v * 100) / 100.0;
}
public static void main(String[] args) {
double[] prices = {249, 129, 60};
int[] qty = {1, 2, 1};
double sub = subtotal(prices, qty);
double off = discount(sub, "WELCOME50");
double afterOff = sub - off;
double delivery = deliveryFee(afterOff, 5.5);
double tax = round2(afterOff * GST_RATE);
System.out.println("Subtotal : " + sub);
System.out.println("Discount : -" + off);
System.out.println("Delivery : " + delivery);
System.out.println("GST : " + tax);
System.out.println("Total : " + round2(afterOff + delivery + tax));
}
}Output
Subtotal : 567.0 Discount : -100.0 Delivery : 45.0 GST : 23.35 Total : 535.35