Last active
January 9, 2024 10:58
-
-
Save trikitrok/1a1ebcd8571967c82c0b1ac30f25d7f4 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 = 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