簡體   English   中英

如何重構這個函數?

[英]How refactoring this function?

我需要使用 SOLID 或干凈的代碼或設計模式重構此功能,任何人都可以幫助我? 不知道能不能重構的switch

我為解耦創建了新函數,但切換循環讓我發瘋

我添加了由我創建的自定義函數,hasCorrectSugars 檢查糖的數量是 0,1 或 2 並檢查糖檢查是否存在糖...

我嘗試了重構。 我對$this->checkSugars感到困惑,它與$this->hasCorrectSugars有何不同?

protected function execute(InputInterface $input, OutputInterface $output): int
{
    $this->setDrinkType($input);

    // Unwrap the if statement and return early instead
    if (!in_array($this->drinkType, $this->allowedDrinkTypes)) {
        $output->writeln('The drink type should be tea, coffee or chocolate');
        return 0;
    }

    // Have a map of the costs of each drink type
    // This could be member variable, i.e. $this->drinkCosts
    $drinkCosts = [
        'tea' => 0.4,
        'coffee' => 0.5,
        'chocolate' => 0.6
    ];

    $money = $input->getArgument('money');

    $drinkCost = $drinkCosts[$this->drinkType];
    if ($money < $drinkCost) {
        $output->writeln('The ' . $this->drinkType . ' costs ' . $drinkCost);
        return 0;
    }

    // Return early if sugars are not correct
    if (!$this->hasCorrectSugars($input)) {
        $output->writeln('The number of sugars should be between 0 and 2');
        return 0;
    }

    $this->checkSugars($input, $output);
    return 0; // Should this not return 1?
}

並重構hasCorrectSugars

protected function hasCorrectSugars($input): bool
{
    $sugars = $input->getArgument('sugars');
    return ($sugars >= $this->minSugars && $sugars <= $this->maxSugars)
}

在函數執行之前我有一個函數configure,我認為它沒有重構,你可以重構這個函數嗎?

protected function configure(): void
{
    $this->addArgument(
        'drink-type',
        InputArgument::REQUIRED,
        'The type of the drink. (Tea, Coffee or Chocolate)'
    );

    $this->addArgument(
        'money',
        InputArgument::REQUIRED,
        'The amount of money given by the user'
    );

    $this->addArgument(
        'sugars',
        InputArgument::OPTIONAL,
        'The number of sugars you want. (0, 1, 2)',
        0
    );

    $this->addOption(
        'extra-hot',
        'e',
        InputOption::VALUE_NONE,
        $description = 'If the user wants to make the drink extra hot'
    );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM