Sub-routines were the first labor-saving devices invented for programmers (DonKnuth, TAOCP Vol 1, p225).
Create a routine when you want to:
- Isolate a complex sequence of instructions from the rest of the program.
- Avoid writing redundant code.
- Limit the effects of changes.
- Group sequences of instructions together.
- Improve performance by optimizing the code in a single place.
- Centralize the control for a task in a single place.
- Hide implementation details of data structures.
- Hide implementation details of global data usage.
- Hide operations on pointers.
- Promote code reuse.
- Make a section of code more readable.
- Isolate non-portable capabilities.
- Isolate complex operations.
Subroutines help you to:
- Reduce complexity
- Remove redundancy
- Hide information
- Reduce coupling
- Increase cohesion
See
CodeComplete (
SteveMcConnell 1993), Section 4
-- KentSchnaith
Snicker. How many of these did we claim were novel
contributions of objects?
-- JimCoplien
I guess we're still trying to solve the same problems. The problems (resulting context?) with the sub-routine solution are:
- In defining a sub-routine we have several associated "rules of the game" (dependencies, interfaces etc.).
- There is no way (other than documentation) to clearly define the "rules of the game".
- There is nothing to stop someone from violating the "rules of the game".
With objects I think we are trying to get the tools (i.e. compiler) to allow us to define the "rules" and help us catch violations of these "rules" earlier in the development cycle.
-- ShalomReich
The most effective referree I have found to catch violators is to identify the pre-conditions of the subroutine or method (and post-conditions, and static conditions) when writing the subroutine, and add ASSERT() statements to catch
violations. If this makes the program too slow, then start at the bottom and prove them out, one routine at a time.
Thanks to DesmondDeSouza at IconComputing for teaching me how to do this.
-- KentSchnaith
See CallingConvention JumpSubRoutine ProcedureWithNoArguments