Skip to content

Instantly share code, notes, and snippets.

@mcsee
Last active June 3, 2025 02:49
Show Gist options
  • Save mcsee/610e138b0ea61252ea4c40cb4e1bd494 to your computer and use it in GitHub Desktop.
Save mcsee/610e138b0ea61252ea4c40cb4e1bd494 to your computer and use it in GitHub Desktop.
This gist belongs to Clean Code Cookbook http://cleancodecookbook.com By Maximiliano Contieri http://maximilianocontieri.com
public class ShoppingCart {
private List<Item> items = new ArrayList<>();
private Coupon coupon = null;
public void addItem(Item item) {
this.items.add(item);
}
public void redeemCoupon(Coupon coupon) {
this.coupon = coupon;
}
public double total() {
double total = 0;
for (Item item : this.items) {
total += item.price();
}
// This a polluted IF and null check
if (this.coupon != null) {
total -= this.coupon.discount();
}
return total;
}
public boolean hasUnsavedChanges() {
// Explicit null check
return !this.items.isEmpty() || this.coupon != null;
}
public boolean hasCoupon() {
return this.coupon != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment