Homework 4

The midterm presented students with the following code snippet:

 

def averageAge(people):
    total = 0
    for p in people:
        total += p.getAge()
    return total / len(people)

 

We assumed that this code appeared in a system with an abstract base class Person that defined a method called getAge() that when appearing in a Person subclass would return the age of the person it represents. We further assumed that the people parameter of averageAge pointed at a collection of Person instances (rather, instances of Person subclasses) and that it would return the average age of the people contained in that collection.

 

The question asked you to describe what you could do to cause averageAge() to return a meaningless answer without modifying its code directly. While several students came up with clever ways to crash the code, the intent of the question was to test student's knowledge on the dangers of polymorphism when a subclass refuses to maintain the contract defined by a superclass.

 

For this homework assignment, write a program that creates two subclasses of Person, one that is well behaved and one that is malicious with respect to the contract defined by Person.getAge(). Write test code that creates two collections, one filled with well-behaved people and one filled with a combination of well-behaved and malicious people. Pass both collections to averageAge() and have your program print out both the expected result and the actual result of calling averageAge().

 

Note: in order to determine what the expected result of the call should be, you should ensure that Person has a setAge() method that allows you to set its age to a known state.

 

This assignment is worth 2 extra credit points. Most students will receive only one point; only the highest quality answers will receive two points. This assignment is due Tuesday, October 28th, at 11:55 PM. Upload a single zip file to the moodle by that date containing your code and a README file describing your solution and how to run it. Note: As with previous assignments, you may use any OO programming language that you want. Just be sure that your assignment follows the requirements above and that the averageAge() method is unchanged other than to translate it to the appropriate syntax of the language you choose.

 

Any questions? Send them to Prof. Anderson

 

Recall that you must not work with other students on this assignment. To remind you of this, please include the following pledge at the top of your README file: "On my honor as a University of Colorado at Boulder student, I have neither given nor received unauthorized assistance on this work."

© Kenneth M. Anderson, 2008