Clean Code书籍中java与Python版本的示例 - Code Review

20-08-08 banq

当我开始阅读Robert Martin的Clean Code。我正在尝试将他的所有示例“翻译”成Python,因此我可以更好地理解它们,请看以下内容:

书中的Java原始代码:

public class GuessStatisticsMessage {
    private String number;
    private String verb;
    private String pluralModifier;

    public String make(char candidate, int count) {
        createPluralDependentMessageParts(count);
        return String.format(
            "There %s %s %s%s", 
            verb, number, candidate, pluralModifier);
    }

    private void createPluralDependentMessageParts(int count) {
        if (count == 0) {
            thereAreNoLetters();
        } else if (count == 1) {
            thereIsOneLetter();
        } else {
            thereAreManyLetters(count);
        }
    }

    private void thereAreManyLetters(int count) {
        number = Integer.toString(count);
        verb = "are";
        pluralModifier = "s";
    }

    private void thereIsOneLetter() {
        number = "1";
        verb = "is";
        pluralModifier = "";
    }

    private void thereAreNoLetters() {
        number = "no";
        verb = "are";
        pluralModifier = "s";
    }
}

我的Python版本:

class GuessStatsMessage:
    def __init__(self, candidate, count):
        self.candidate = candidate
        self.count = count
        self.__number = self.__verb = self.__plural_modifier = ''

    def make_message(self):
        self.__create_pluraldependant_message_parts()
        guess_message = (f'There {self.__verb} '
                         f'{self.__number} '
                         f'{self.candidate}{self.__plural_modifier} ')
        print(guess_message)

    def __create_pluraldependant_message_parts(self):
        if self.count == 0:
            self.__there_are_no_letters()
        elif self.count == 1:
            self.__there_is_one_letter()
        else:
            self.__there_are_many_letters()

    def __there_are_no_letters(self):
        self.__number = 'no'
        self.__verb = 'are'
        self.__plural_modifier = 's'

    def __there_is_one_letter(self):
        self.__number = '1'
        self.__verb = 'is'
        self.__plural_modifier = ''

    def __there_are_many_letters(self):
        self.__number = str(self.count)
        self.__verb = 'are'
        self.__plural_modifier = 's'

 

                   

猜你喜欢