-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbad_design.php
More file actions
87 lines (70 loc) · 2.2 KB
/
bad_design.php
File metadata and controls
87 lines (70 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/*
* Child classes should behave like their parent classes without unexpected changes.
* If a subclass changes the expected behavior of the parent class, it violates LSP.
*
*
* Here we have a base class PaymentMethod and create "CreditPayment" and
* "CashOnDelivery" Subclasses, both should work wherever "PaymentMethod"
* is expected - pay & refund. But "CashOnDelivery" would break this principle
* since we can't expect refund from CashOnDelivery.
*
*/
declare(strict_types = 1);
abstract class PaymentMethod
{
abstract public function pay(float $amount) : string;
abstract public function refund(float $amount) : string;
}
class CreditPayment extends PaymentMethod
{
public function pay( float $amount) : string
{
return 'Paid $' . $amount . ' with Credit Card.';
}
public function refund(float $amount): string
{
return 'Refunded $' . $amount . ' to Credit Card.';
}
}
class CashOnDelivery extends PaymentMethod
{
public function pay(float $amount): string
{
return 'Cash of $' . $amount . ' will be collected on delivery.';
}
// Problem: Cash on Delivery can't refund
public function refund(float $amount): string
{
throw new \Exception('Refund not supported for Cash On Delivery.' . PHP_EOL);
}
}
class PaymentProcess
{
public function processPay(PaymentMethod $payment, float $amount) : void
{
echo $payment->pay($amount) . PHP_EOL;
}
public function processRefund(PaymentMethod $payment, float $amount) : void
{
echo $payment->refund($amount) . PHP_EOL;
}
}
// Usages
try {
$card = new CreditPayment();
$paymentprocess = new PaymentProcess();
$paymentprocess->processPay($card, 500.67); // Works
$paymentprocess->processRefund($card, 500.67); // Works
$cod = new CashOnDelivery();
$paymentprocess->processPay($cod, 500.67); // Works
$paymentprocess->processRefund($cod, 500); // Breaks: Unexpected exception.
} catch (\Throwable $th) {
print $th->getMessage();
}
/* Output::
Paid $500.67 with Credit Card.
Refunded $500.67 to Credit Card.
Cash of $500.67 will be collected on delivery.
Refund not supported for Cash On Delivery.
*/