Using a utility method to construct objects of different types - Python
Archive - Originally posted on "The Horse's Mouth" - 2008-05-17 06:50:17 - Graham EllisWhen you call an object's constructor method, you'll be allocating memory to hold the information about that object and the method will return an instance variable - a reference with which you can later refer back to the object.
That's good as far as it goes - but there are times when you'll have data from which you want to construct an object but the object type is hidden within the data. For example, I could have a file of data record like
Estate Agent, 01380 724040, 2500
and
Graham, 600
where the lines with three comma separated fields are customers, and the lines with two comma separate fields are team members. And you want to construct two different types of object, depending on the data.
The first possible answer is to have your application program work out from each data line which particular object type you need to build for each piece of data but that is messy as it means that the data-specific code that should be common to all uses of the class has to migrate outside the class to the application, with serious issues about code duplication, reuse and maintainability.
The preferable alternative is for you to provide a utility method within(Java, etc) or in association with (Python, etc) the class coding which takes the data record and constructs either a "customer" or a "team member" record, and returns whichever instance variable type it finds to be appropriate.
I have an example of this principle in the Intermediate Objects in Python module from our Python Programming Course.
The "control case" - the example which shows the decision made in the application code without the utility method reads as follows:
operation.append(customer("Local Council","01225 776655",10000))
operation.append(customer("Estate Agent","01380 724040",2500))
operation.append(employee("Charlie",20))
operation.append(employee("Graham",600))
which is modified to read as follows when you use utility method calls:
operation.append(fing("Local Council, 01225 776655, 10000"))
operation.append(fing("Estate Agent, 01380 724040, 2500"))
operation.append(fing("Charlie, 20"))
operation.append(fing("Graham, 600"))
Which looks a subtle enough change when the data is a simple example, but becomes significant when the number of object types increases and the data is read from file.
Here's the code of the utility method, which will be stored and maintained with the classes:
def fing(about):
bits = about.split(", ")
if len(bits) == 3:
return customer(bits[0],bits[1],int(bits[2]))
return employee(bits[0],int(bits[1]))
See control example - source and example with utility method - source