Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active June 19, 2023 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trikitrok/53e0a55c5728bfec7ffcc4cdd6ef403f to your computer and use it in GitHub Desktop.
Save trikitrok/53e0a55c5728bfec7ffcc4cdd6ef403f to your computer and use it in GitHub Desktop.
// Adapted from Code Smell: Null Check, Joe Eames https://medium.com/thinkster-io/code-smell-null-check-a0c4851fafbf
class DiscountCalculator {
private static final float DEFAULT_DISCOUNT = 1.0f;
// ...
public float getDiscount(String customerId) {
Customer customer = customerRepository.findBy(customerId);
if(customer == null) {
return DEFAULT_DISCOUNT;
}
return customer.getEarnedDiscount();
}
}
class Orders {
// ...
public void processOrder(String customerId, Order order) {
Customer customer = customerRepository.findBy(customerId);
if(customer != null) {
customer.addToOrdersHistory(order);
}
// more logic that does not use customer...
}
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
class NotFoundCustomer implements Customer {
private static final float DEFAULT_DISCOUNT = 1.0f;
//...
public float getEarnedDiscount() {
return DEFAULT_DISCOUNT;
}
public void addToOrdersHistory(Order order) {
}
}
class DiscountCalculator {
// ...
public float getDiscount(String customerId) {
Customer customer = customerRepository.findBy(customerId);
return customer.getEarnedDiscount();
}
}
class Orders {
// ...
public void processOrder(String customerId, Order order) {
Customer customer = customerRepository.findBy(customerId);
customer.addToOrdersHistory(order);
// more logic ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment