When to Use Object-oriented Programming
[
126
]
Identifying objects is a very important task in object-oriented analysis and
programming. But it isn't always as easy as counting the nouns in a short paragraph,
as we've been doing. Remember, objects are things that have both data and behavior.
If
we are working only with data, we are often better off storing it in a list, set,
dictionary, or some other Python data structure (which we'll be covering thoroughly
in
Chapter 6
,
Python Data Structures
). On the other hand, if we are working only with
behavior,
but no stored data, a simple function is more suitable.
An object, however, has both data and behavior. Proficient Python programmers
use built-in data structures unless (or until) there is an obvious need to define a class.
There is no reason to add an extra level of abstraction if it doesn't help organize
our code. On the other hand, the "obvious" need is not always self-evident.
We can often start our Python programs by storing data in a few variables. As the
program expands, we will later find that we are passing the same set of related
variables to a set of functions. This is the time to think about
grouping both variables
and functions into a class. If we are designing a program to model polygons in two-
dimensional space, we might start with each polygon being represented as a list of
points. The points would be modeled as two-tuples (
x
,
y
) describing where that point
is located. This is all data, stored in a set of nested data structures (specifically, a list
of tuples):
square = [(1,1), (1,2), (2,2), (2,1)]
Now, if we want to calculate the distance around
the perimeter of the polygon, we
simply need to sum the distances between the two points. To do this, we also need a
function to calculate the distance between two points. Here are two such functions:
import math
def distance(p1, p2):
return math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)
def perimeter(polygon):
perimeter = 0
points = polygon + [polygon[0]]
for i in range(len(polygon)):
perimeter += distance(points[i], points[i+1])
return perimeter
Now, as object-oriented programmers, we clearly recognize that a
polygon
class
could encapsulate the list of points (data) and the
perimeter
function (behavior).
Further, a
point
class,
such as we defined in
Chapter 2
,
Objects in Python
, might
encapsulate the
x
and
y
coordinates and the
distance
method. The question is:
is it valuable to do this?
www.it-ebooks.info