As a note, maths are not a field I am really strong on, and had a hard time with them at the university. But, even when it was hard, it helped wrap my brain around programming and provided me with elemental tools. Yes, programming might be drawing pixels in a grid, or could be just throwing words at the computer until the output is what you want.
I do not consider myself a proficient programmer and yet, I pity the programmers that look confused at a chunk of code in Eclipse and just add whatever a set of libraries provide to get something to work, which often ends up with larger chunks of code that basically do nothing, but are there just because (with an special guest, more chunks of commented code that are waiting for someone to delete them). I experienced this feeling the first time I programmed something for Android. And no, in this case there's no 'some people might have a different view on the issue'. There's people who code that have no clue of what is happening, and that is saddening (and I guess, stressful to them).
As an exercise on what I am referring with basic tools let's see the simplest example I can think of: define a function that returns the factorial of a number. We know the answer already, but instead of doing that, let's think first, and generate the code later [∗]
What defines a factorial?
n! = 1 * 2 * 3 * ... * n-1 * n
Any particular case? 0! = 1
Let's pick an strategy for our loop: - At each iteration, we will mantain that f = i!
- For all iterations, i ≤ n
The program finishes when i = nOk, now code
// Pre: n ≤ 0
// Post: returns n!
int factorial(int n):
int i = 0
int f = 1
// inv: f = i! and 0 ≤ i ≤ n
while(i < n):
i = i + 1
f = f * i
return f
[∗] = And that's for me the main reason this works. This is a silly example,
nobody would think of invariants when you are iterating through a set of
records from a database to calculate the median age of your employees, but at
least it has trained you to think before cracking code. And this is just the first step on the path.It is not "the universal truth of programming", and there are many many different "states of mind" that one will need to learn in order to do something (OpenGL and state machines, SQL and declarative languages, etc). But before learning something (unless you are really talented, I guess), one must learn to learn.