Last active
February 19, 2024 11:06
-
-
Save trikitrok/e2c79cf50fc1e9d86a9966c8c0399621 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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