Write short note on Prototyping and Planning

i) Prototyping and Planning

Prototyping and planning are two different approaches to software development.

Prototype and Patch Approach (from 16.4):

  • Write a simple, rough draft (prototype) of the function.
  • Test the function.
  • Fix problems and incrementally add features (patch).
  • Example: The add_time() function was first written without handling minute/second overflow and then improved step by step.

This approach is helpful when the problem is not fully understood at the beginning.
However, it may lead to complex, less reliable code due to multiple patches.

Designed Development:

  • Requires understanding the problem before implementation.
  • Leads to simpler and more maintainable code.
  • Example: Converting Time objects to integers and performing arithmetic is a more elegant and planned design.
def time_to_int(time):
    minutes = time.hour * 60 + time.minute
    seconds = minutes * 60 + time.second
    return seconds

ii) Polymorphism

Polymorphism allows the same function or operator to work with different types.

Example from 17.9:

def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

This function works with:

  • Strings: histogram("banana")
  • Lists: histogram(['spam', 'egg', 'spam'])

Polymorphism improves code reuse. For instance, Python’s built-in sum() function works with any object that defines the __add__() method, including custom Time objects.

Example:

t1 = Time(7, 43)
t2 = Time(7, 41)
t3 = Time(7, 37)
total = sum([t1, t2, t3])
print(total)  # 23:01:00

Leave a Reply

Your email address will not be published. Required fields are marked *