Last active
September 19, 2023 00:01
-
-
Save trikitrok/2bb1b3daa4bdb37593518e2738a29c08 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 | |
<?php | |
class DiscountCalculator { | |
// ... | |
public function getDiscount(string $customerId) { | |
$customer = $this->customerRepository->findBy($customerId); | |
if($customer == null) { | |
return self::DEFAULT_DISCOUNT; | |
} | |
return $this->$customer->getEarnedDiscount(); | |
} | |
} | |
class Orders { | |
// ... | |
public function processOrder(string $customerId, Order $order) { | |
$customer = $this->customerRepository->findBy($customerId); | |
if($customer != null) { | |
$customer->addToOrdersHistory($order); | |
} | |
// more logic ... | |
} | |
} | |
//-------------------------------------------------------------------- | |
//-------------------------------------------------------------------- | |
<?php | |
interface Customer { | |
public function getEarnedDiscount(): float; | |
public function addToOrdersHistory(Order $order): void; | |
} | |
// some Customer's implementations | |
// ... | |
// Customer's null implementation | |
class NotFoundCustomer implements Customer { | |
private float DEFAULT_DISCOUNT = 1.0; | |
//... | |
public function getEarnedDiscount(): float { | |
return $this->DEFAULT_DISCOUNT; | |
} | |
public function addToOrdersHistory(Order $order): void { | |
} | |
} | |
class DiscountCalculator { | |
private CustomerRepository $customerRepository; | |
function __construct(CustomerRepository $customerRepository) { | |
$this->customerRepository = $customerRepository; | |
} | |
// ... | |
public function getDiscount(string $customerId): float { | |
$customer = $this->customerRepository->findBy($customerId); | |
return $customer->getEarnedDiscount(); | |
} | |
} | |
class Orders { | |
private CustomerRepository $customerRepository; | |
function __construct(CustomerRepository $customerRepository) { | |
$this->customerRepository = $customerRepository; | |
} | |
// ... | |
public function processOrder(string $customerId, Order $order): void { | |
$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