Skip to content

Instantly share code, notes, and snippets.

@mcsee
Last active June 3, 2025 02:48
Show Gist options
  • Save mcsee/f212507baeb4654b70a3f11270fd9758 to your computer and use it in GitHub Desktop.
Save mcsee/f212507baeb4654b70a3f11270fd9758 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 final List<Item> items = new ArrayList<>();
// This version uses Optionals
// Not all programming languages support this feature
private Optional<Coupon> coupon = Optional.empty();
public void addItem(Item item) {
items.add(item);
}
public void redeemCoupon(Coupon coupon) {
// You need to understand how optionals work
this.coupon = Optional.ofNullable(coupon);
}
public boolean hasUnsavedChanges() {
return !items.isEmpty() || coupon.isPresent();
}
public boolean hasCoupon() {
return coupon.isPresent();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment