Modular Programming

Created
Tags

Modular programming and non-modular programming are two ways of accomplishing the same output.

  • Modular programming is more efficient and it’s the way you must program from now on.
  • Non-modular programming is purely chronological; It is less efficient as you cannot create functions (modules) to break the program down.

Non-Modular Programming:

#calculate the speed
#input
distance = int(input("how far has the car travelled? (in miles): "))
time = float(input("how long (in hours) did it take to trvel this distance?"))
#process
speed = distance/time
#output
print("to travel", distance,"miles in",time,"hours required a speed of",speed,"mph")

Modular (Better) Programming:

def inputs(): #we break the program down into three sub-programs, starting with collecting the inputs.
    distance = int(input("how many miles did you travel?"))
    time = float(input("how long in hours did it take?"))
    return distance, time

def process(distance,time): #then we calculate the speed.
    speed = distance/time
    return speed
    
def output(speed,distance,time):
    print("to travel", distance, "miles in", time, "hours, you traveled at a speed of", speed, "miles per hour")

distance, time = inputs() #this might seem arbitrary at first, but there is a simple formula to make this simple. 
speed = process(distance,time)
output(speed,distance,time)

ModularNon-Modular
It efficiently and methodically requires you to dissect the program into sub-programs, making it readable.The whole program reads like one continuous block and therefore is difficult to understand.
Errors are easier to isolate to particular modules.Since the code is more difficult to understand, errors are harder to isolate as code becomes mixed together.
Easier to modify one particular module without affecting the rest of the program.Changing one part of the code can easily affect more parts of the program inadvertently.

Here is the simple formula you can use to call a function:

return_variables = function_name(in_parameters)

distance, time = inputs() #this might seem arbitrary at first, but there is a simple formula to make this simple. 
speed = process(distance,time) #the out parameter.
output(speed,distance,time) #there is no return for this one. Just call the function.