From single block to structure and object oriented programming
Archive - Originally posted on "The Horse's Mouth" - 2015-12-02 18:00:17 - Graham EllisIf you're writing a very short, one-off program, you're likely to mix your calcualtion details in with your data input / output and data format handling - "quick and easy" - for example, code (Python 2.7 and 3.x) [here].
But as your application grows, and the code grows, a single block becomes less managable, you lack "test points" to test it in sections, the detailed data algorithms are in-line with the managemnt which makes it hard to look after if each section's got a different lead programmer, and the algorithms can't be shared between programs unless you copy and paste - and if you copy and paste, your duplicating any program bugs you have, and doubling up future work when you upgrade your algorithms too.
The first solution I'm offering you today is to move your algorithms out into named blocks of code (they'll be called "subroutines", "functions", "procedures", "macros", "commands" or "methods" depending on the language you're using - for my short example, the code becomes a little longer but it also becomes much more managable - see [here].
In that first solution, the data remains in the main program and is passed to each of the functions as required to be manipuated. So there remains quite a data management task in your main application as it grows. My second (and improved) solution is to pass in the data to a single named block of code intially, then pass around just a handle to each of the functions that access that data. Not only does this save you holding and managing the data in the main program, but it also provides a robustness against errors in that it will only let you perform sensible, predefined tasks on the data. There's an example of this technique [here].
To keep the examples neat and in a single window, I've kept the detailed logic in my above examples in the same file, but moved it above the main control code ... in a live application, you would use separate files for the "controller" and the "model" - in the Python example using the import or from commands in the main code to load the detailed logic when required.
Example written during today's Python course.
P.S.
The default way - "Single block coding"
The first suggestion - "Struuctured coding"
The second suggestion - "Object Oriented Programming"