Making the Application More Modular

We've done a good jobs ot keeping the application modular, but we car do Tetter. First, we're going to abstract out the differences belween a flit-file modd ard m database model . 'Then wera go irg to add sSatabase support with as few charges as possMe to AddressMrdel.py.

What we'll do is move tie file-specific dependencies from AddressModel's cossirtcior tsY puS readAddresses () and writeAddresses () in a module called AddressFileUjils.py. All modified ard new files will be in a directory called AddressBrrk.2. Here's the origiral AddressModel constmctor:

class AddressModel(AbstractTableModel, ListModel): """The AddressModel is both a ListModel and a TableModel."""

"""Initialize the Address model. Read the dictionary from the file."""

# holds the dictionary of addresses. self.dict = None

# holds the sorted list of names,

# which are keys into the dictionary. self.list = None

# to hold list of ListModelListeners self.listeners = []

# Read the addresses from the file.

# holds the file name that

# holds the addresses self.fname=".\\addr.dat"

self.dict = readAddresses(self.fname)

# Store the sorted list of names. self.list = self.dict.keys()

self.list.sort()

def writeAddresses(self):

"""Write the address data to the file.""" writeAddresses(self.fname, self.dict)

Here is the constructor as modified:

class AddressModel(AbstractTableModel, ListModel): """The AddressModel is both a ListModel and a TableModel."""

"""Initialize the Address model. Read the dictionary from the file."""

#holds the dictionary of addresses. self.dict = None

#holds the sorted list of names,

# which are keys into the dictionary self.list = None

#to hold list of ListModelListeners self.listeners = []

# Read the addresses

# from the Address utility. self.dict = readAddresses()

def writeAddresses(self)

"""Write the address data to the file.""" writeAddresses(self.diet)

The following are the changes we made to readAddresses () and writeAddresses (), which are now in their own module, AddressFileUtils.py. Notice that both functions have a default value for filename that they didn't have before.

def readAddresses(filename=".\\addr.dat"):

def writeAddresses(dict, filename=".\\addr.dat", bin=0):

The result, essentially, i s that all file-based functional ity has been encapsulated out of AddressModel. The next step is testing.

Was this article helpful?

0 0

Post a comment