Last active
January 16, 2021 09:53
-
-
Save radzserg/74b6f6423302176d51d4e3e7c439460a 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
# step #1 - Inline code inside a consumer | |
# code is simple enough, consumer is simple enough | |
class OrderService { | |
public processOrder(Order order) { | |
// validate input | |
let totalPrice = orderData.items.reduce( (totalPrice, orderItem) => totalPrice + (orderItem.price * orderItem.quantity)); | |
totalPrice = totalPrice + totalPrice * 0.05; // add service commission | |
// process payment | |
// update order state in DB | |
// notify warehouse | |
} | |
} | |
# step #2 - move code to consumer's private function | |
# the consumer's code has increased and we do not want to extend it further | |
# | |
class OrderService { | |
public processOrder(Order order) { | |
// validate input | |
...... | |
...... | |
...... | |
...... | |
...... | |
const total = this.calculateTotal(orderData); | |
// process payment | |
...... | |
...... | |
...... | |
...... | |
...... | |
...... | |
// update order state in DB | |
...... | |
...... | |
...... | |
...... | |
...... | |
// notify warehouse | |
...... | |
...... | |
...... | |
...... | |
...... | |
...... | |
...lines & lines of code | |
} | |
private calculateTotal(orderData): number { | |
let totalPrice = orderData.items.reduce( (totalPrice, orderItem) => totalPrice + (orderItem.price * orderItem.quantity)); | |
totalPrice = totalPrice + totalPrice * 0.05; | |
} | |
} | |
# step #3 | |
# we receive requests to change the calculation algorithm, which do not affect changes within the OrderService | |
class OrderService { | |
public processOrder(Order order) { | |
...... | |
const total = (new OrderCalculator()).calculateTotal(orderData); | |
...... | |
} | |
} | |
class OrderCalculator { | |
public calculate(orderData: any) { | |
let totalPrice = orderData.items.reduce( (totalPrice, orderItem) => totalPrice + (orderItem.price * orderItem.quantity)); | |
let applicationFee = 1; | |
if (orderData.customer.plan === Plan.Basic) { | |
applicationFee = 0.05 | |
} else if (orderData.customer.plan === Plan.Basic) { | |
applicationFee = 0.04 | |
} | |
let paymentFee = 0; | |
if (orderData.user.country === Country.US) { | |
paymentFee = 5; | |
} | |
if (orderData.user.country === Country.GB) { | |
paymentFee = 5.5; | |
} | |
// etc | |
return totalPrice + totalPrice * applicationFee + paymentFee; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment