Upload
damian-charles
View
212
Download
0
Embed Size (px)
Citation preview
Modular Programming
Modular Programming (1/6) Modular programming
Goes hand-in-hand with stepwise refinement and incremental development
Makes the code easier to develop, test and debug Promotes reusability of codes
In general a problem is solved in 3 steps: input computation output.
© CS1101 (AY2009-2010 Semester 1) Week6 - 2
Modular Programming (2/6) Write a separate module to perform the
computation step. If the computation is complex, it should be
further split into smaller steps and each step performed by a module.
A ‘module’ Should be well-defined Should do one task
© CS1101 (AY2009-2010 Semester 1) Week6 - 3
Modular Programming (3/6) A well-defined module
Has a good name (for readability and documentation) Has a clear interface (what parameters does it take?) May pass back to its caller no result or a single result (what
value does it return?)
Example: setColour(int c)
Example: getColour()
© CS1101 (AY2009-2010 Semester 1) Week6 - 4
void setColour(int c) { int colour = c;}
Takes in integer c.Does not return any value (void).
int getColour() { return colour;}
Takes in no parameter.Returns an integer
Modular Programming (4/6) Advantages of modular programming:
Easy to replace E.g.: When you discover a better algorithm for isPrime(int),
you just replace that method without affecting any other parts of the program or other programs.
Easy to reuse E.g.: Suppose you want to write a program to count the
number of prime numbers between two integers a and b. Compare how you would need to modify
© CS1101 (AY2009-2010 Semester 1) Week6 - 5
Modular Programming (5/6) Reusability of code
If isPrime(int) is a very commonly used method, we could even go a step further… Ie . It is so short and sweet!
Any other application that requires the isPrime(int) method can use the method in a similar fashion.
© CS1101 (AY2009-2010 Semester 1) Week6 - 6
7
Advantages of Modular Programming
• Extension of function modularity: Build, test, debug in isolation from other modules.
• Prevent access to private functions and data – prevent misuse.
• Hide difficult algorithms behind a set of interfaces.• Hide non-portable code behind a portable interface. Can
change internals without changing client code.• Enable teams to work on same program. Each works on a
different module.• Modules are often reusable – libraries.