Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active January 9, 2024 10:58
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/1a1ebcd8571967c82c0b1ac30f25d7f4 to your computer and use it in GitHub Desktop.
Save trikitrok/1a1ebcd8571967c82c0b1ac30f25d7f4 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
const DEFAULT_DISCOUNT = 1.0;
class DiscountCalculator {
constructor(customerRepository) {
this.customerRepository = customerRepository;
}
// ...
getDiscount(customerId) {
const customer = this.customerRepository.findBy(customerId);
if (customer == null) {
return DEFAULT_DISCOUNT;
}
return customer.getEarnedDiscount();
}
}
class Orders {
constructor(customerRepository) {
this.customerRepository = customerRepository;
}
// ...
processOrder(customerId, order) {
const customer = this.customerRepository.findBy(customerId);
if (customer != null) {
customer.addToOrdersHistory(order);
}
// more logic ...
}
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
// The interface of Customer objects has two methods in it (shown in pseudocode):
// * getEarnedDiscount(): number;
// * addToOrdersHistory(order: Order): void;
// some Customer's implementations
// ...
// Null Customer's implementation
class NotFoundCustomer implements Customer {
DEFAULT_DISCOUNT = 1.0;
//...
public getEarnedDiscount(): number {
return this.DEFAULT_DISCOUNT;
}
public addToOrdersHistory(order: Order): void {
}
}
class DiscountCalculator {
constructor(customerRepository) {
this.customerRepository = customerRepository;
}
// ...
getDiscount(customerId) {
const customer = this.customerRepository.findBy(customerId);
return customer.getEarnedDiscount();
}
}
class Orders {
constructor(customerRepository) {
this.customerRepository = customerRepository;
}
// ...
processOrder(customerId, order): void {
const customer = this.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