Sometimes the only object you need is a function

Now we'll show how it's quite possible to write nice object-oriented code without needing classes. We have a requirement to produce boarding cards for our passengers in alphabetical order. However, we realize that the Flight class is probably not a good home for details of printing boarding passes. We could go ahead and create a BoardingCardPrinter class, although that is probably overkill. Remember that functions are objects too and are perfectly sufficient for many cases. Don't feel compelled to make classes without good reason.

Rather than have a card printer query all the passenger details from the flight, we'll follow the object-oriented design principle of "Tell! Don't Ask." and have the Flight tell a simple card printing function what to do.

First the card printer, which is just a module level function:

def console_card_printer(passenger, seat, flight_number, aircraft):
output = "| Name: {0}"
" Flight: {1}"
" Seat: {2}"
" Aircraft: {3}"
" |".format(passenger, flight_number, seat, aircraft)
banner = '+' + '-' * (len(output) - 2) + '+'
border = '|' + ' ' * (len(output) - 2) + '|'
lines = [banner, border, output, border, banner]
card = ' '.join(lines)
print(card)
print()

A Python feature we're introducing here is the use of line continuation backslash characters, , which allow us to split long statements over several lines. This is used here, together with implicit string concatenation of adjacent strings, to produce one long string with no line breaks.

We measure the length of this output line, build some banners and borders around it and, concatenate the lines together using the join() method called on a newline separator. The whole card is then printed, followed by a blank line. The card printer doesn’t know anything about Flights or Aircraft – it's very loosely coupled. You can probably easily envisage an HTML card printer that has the same interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset