Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active February 19, 2024 11:06
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/e2c79cf50fc1e9d86a9966c8c0399621 to your computer and use it in GitHub Desktop.
Save trikitrok/e2c79cf50fc1e9d86a9966c8c0399621 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: number = 1.0;
class DiscountCalculator {
private customerRepository: CustomerRepository;
constructor(customerRepository: CustomerRepository) {
this.customerRepository = customerRepository;
}
// ...
getDiscount(customerId: string): number {
const customer = this.customerRepository.findBy(customerId);
if (customer == null) {
return DEFAULT_DISCOUNT;
}
return customer.getEarnedDiscount();
}
}
class Orders {
private customerRepository: CustomerRepository;
constructor(customerRepository: CustomerRepository) {
this.customerRepository = customerRepository;
}
// ...
processOrder(customerId: string, order: Order): void {
const customer = this.customerRepository.findBy(customerId);
if (customer != null) {
customer.addToOrdersHistory(order);
}
// La otra versión
// customer?.addToOrdersHistory(order);
// more logic ...
}
}
//--------------------------------------------------------------------
//--------------------------------------------------------------------
interface Customer {
getEarnedDiscount(): number;
addToOrdersHistory(order: Order): void;
}
// some Customer's implementations
// ...
// Null Customer's implementation
class NotFoundCustomer implements Customer {
private DEFAULT_DISCOUNT: number = 1.0;
//...
public getEarnedDiscount(): number {
return this.DEFAULT_DISCOUNT;
}
public addToOrdersHistory(order: Order): void {
}
}
class DiscountCalculator {
private customerRepository: CustomerRepository;
constructor(customerRepository: CustomerRepository) {
this.customerRepository = customerRepository;
}
// ...
getDiscount(customerId: string): number {
const customer = this.customerRepository.findBy(customerId);
return customer.getEarnedDiscount();
}
}
class Orders {
private customerRepository: CustomerRepository;
constructor(customerRepository: CustomerRepository) {
this.customerRepository = customerRepository;
}
// ...
processOrder(customerId: string, order: 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