Skip to Content
Course content

229: Building a Simple E-Commerce Cart System

Click on the "Edit" button in the top corner of the screen to edit your slide content.

We've spent a lot of time on the theory of collections and object-oriented design, but now it's time to glue it all together. We're going to build a small e-commerce cart system. Now, in a production environment, you'd be dealing with databases, API endpoints, and complex state management, but for this lesson, we're focusing on the core business logic: how to manage a set of items and calculate a total accurately.

Setting up the Data Models

First, we need a way to represent what we're actually selling. I'll start with a simple Product class. It doesn't need much—just a name and a price. I'm using double for the price here for simplicity, though if this were a real banking app, I'd be screaming at you to use BigDecimal to avoid floating-point errors.

public class Product {
    private final String name;
    private final double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() { return name; }
    public double getPrice() { return price; }
}

Next, we need a CartItem. A common mistake I see is people putting the quantity directly into the Product class. Don't do that. A product's price doesn't change just because someone wants three of them. We need a wrapper that associates a product with a specific quantity for a specific user's session.

public class CartItem {
    private final Product product;
    private int quantity;

    public CartItem(Product product, int quantity) {
        this.product = product;
        this.quantity = quantity;
    }

    public void addQuantity(int amount) { this.quantity += amount; }
    public Product getProduct() { return product; }
    public int getQuantity() { return quantity; }
}

Building the Cart Logic

Now for the main event: the ShoppingCart class. I'll use an ArrayList to hold our CartItem objects. My goal here is to create a method that lets us add products to the cart easily.

import java.util.*;

public class ShoppingCart {
    private final List<CartItem> items = new ArrayList<>();

    public void addItem(Product product, int quantity) {
        items.add(new CartItem(product, quantity));
    }

    public List<CartItem> getItems() {
        return items;
    }
}

Fixing the Duplicate Item Bug

I just noticed a problem with the code I wrote above. If a user adds a "Mechanical Keyboard" to their cart, and then adds another "Mechanical Keyboard" later, my current addItem method just adds a second CartItem to the list. That's messy. When the user looks at their checkout page, they shouldn't see the same item listed three times; they should see one item with a quantity of three.

I need to pivot. Instead of blindly adding to the list, I should check if the product already exists in the cart first. If it does, I'll just bump up the quantity of the existing item.

public void addItem(Product product, int quantity) {
    for (CartItem item : items) {
        if (item.getProduct().equals(product)) {
            item.addQuantity(quantity);
            return; // Exit the method once we've updated the existing item
        }
    }
    // If we get here, it's a new product for this cart
    items.add(new CartItem(product, quantity));
}

Tallying Up the Total

Finally, we need to know how much the customer owes. I'll implement a calculateTotal method. I'm going to use a simple for-each loop here because it's readable and efficient for a small list of items.

public double calculateTotal() {
    double total = 0;
    for (CartItem item : items) {
        total += item.getProduct().getPrice() * item.getQuantity();
    }
    return total;
}

And that's it. We've built a system that handles product definitions, manages quantities without duplicating entries, and calculates a final price. It's a small building block, but this pattern—separating the entity (Product) from the session state (CartItem)—is something you'll use constantly in professional Java development.




📋 Practical Task

Implementing a Percentage-Based Discount Voucher

Now it's your turn to extend the system. Your task is to modify the ShoppingCart class to support a discount voucher system.

  • Add a private field to ShoppingCart called discountPercentage (a double, e.g., 0.10 for 10%).
  • Create a method called applyVoucher(double percentage) that updates this field.
  • Modify the calculateTotal() method so that it applies the discount to the final sum before returning the value. For example, if the total is $100 and the discount is 0.10, the method should return $90.00.
  • Test your implementation by adding multiple items to a cart, applying a 20% discount, and printing the final total to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.