I started reading Robert Martin's Clean Code. I'm trying to "translate" all his examples into Python, so I can understand them better since my knowledge of Python is greater than that of Java.
This class formats a count in into a natural English sentence:
Java original code of the book
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"; } }
My Python version
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'
It should be used as follows:
message = GuessStatsMessage('Foo', 10)
message.make_message()
# output: There are 10 Foos
__str__()
method and maybe a__format__()
method instead ofmake_message()
. \$\endgroup\$__double_underscore
in Python. But be careful: Any identifier of the form__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, where classname is the current class name with leading underscore(s) stripped. But__private
names don't work the same way as in Java. Actually I don't think this is a good practice in Python at all. \$\endgroup\$GuessStatsMessage
class. @PéterLeéh \$\endgroup\$