Skip to content

Instantly share code, notes, and snippets.

@CesarChaMal
Forked from mauricioaniche/Basket.java
Created December 6, 2019 18:42
Show Gist options
  • Save CesarChaMal/383a91e8ffeaa914987df83768b5608b to your computer and use it in GitHub Desktop.
Save CesarChaMal/383a91e8ffeaa914987df83768b5608b to your computer and use it in GitHub Desktop.
TDD for Professionals - Discount example
package module1.exercise.discount;
import java.util.List;
public class Basket {
private double amount;
private List<Item> items;
public Basket(List<Item> itemss) {
this.items = itemss;
sumItems();
}
private void sumItems() {
for(Item item : items) {
amount += item.getTotalPrice();
}
}
public void subtract(double amount) {
this.amount -= amount;
}
public double getAmount() {
return amount;
}
public int qtyOfItems() {
int qty = 0;
for(Item item : items) {
qty+= item.getQty();
}
return qty;
}
public boolean has(String product) {
for(Item item : items) {
if(item.getName().equals(product)) return true;
}
return false;
}
}
package module1.exercise.discount;
public class DiscountApplier {
public void apply(Basket basket) {
boolean ok = discountPerProduct(basket);
if(!ok) discountPerAmount(basket);
}
private boolean discountPerProduct(Basket basket) {
if(basket.has("MACBOOK") && basket.has("IPHONE")) {
basket.subtract(basket.getAmount() * 0.15);
return true;
}
if(basket.has("NOTEBOOK") && basket.has("WINDOWS PHONE")) {
basket.subtract(basket.getAmount() * 0.12);
return true;
}
if(basket.has("XBOX")) {
basket.subtract(basket.getAmount() * 0.7);
return true;
}
return false;
}
private void discountPerAmount(Basket basket) {
if(basket.getAmount()<=1000 && basket.qtyOfItems() <= 2) {
basket.subtract(basket.getAmount() * 0.02);
}
else if(basket.getAmount() > 3000 && basket.qtyOfItems() < 5 && basket.qtyOfItems() > 2) {
basket.subtract(basket.getAmount() * 0.05);
}
else if(basket.getAmount() > 3000 && basket.qtyOfItems() >= 5) {
basket.subtract(basket.getAmount() * 0.06);
}
}
}
package module1.exercise.discount;
public class Item {
private final String name;
private final int qty;
private final double unitPrice;
public Item(String name, int qty, double price) {
this.name = name;
this.qty = qty;
this.unitPrice = price;
}
public String getName() {
return name;
}
public int getQty() {
return qty;
}
public double getUnitPrice() {
return unitPrice;
}
public double getTotalPrice() {
return unitPrice * qty;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment