Junior — Senior
Code restructuring in an online store system
livecode
Task condition
In the online store project, there are several classes describing products and their storage. Two main operations are implemented: reserving a product and replenishing its quantity. It is required to rewrite the code so that it is ready for further extension and better adheres to encapsulation principles.
namespace MyAwesomeShop;
final readonly class ProductId {}
final class NotEnoughProductInStock extends \Exception {}
interface ProductRepository
{
public function get(ProductId $productId): Product;
public function save(Product $product): void;
}
final class Product
{
public int $quantity = 0;
public function __construct(
public readonly ProductId $productId,
public string $title,
public string $description = '',
) {}
}
final readonly class InventoryService
{
public function __construct(
private ProductRepository $repository,
) {}
public function reserve(ProductId $itemId, int $amount): void
{
$product = $this->repository->get($itemId);
if ($product->quantity < $amount) {
throw new NotEnoughProductInStock();
}
$product->quantity -= $amount;
$this->repository->save($product);
}
public function replenish(ProductId $itemId, int $amount): void
{
$product = $this->repository->get($itemId);
$product->quantity += $amount;
$this->repository->save($product);
}
}