Karen Guffey wrote:First, as I was writing the program & came to the end of the method, I realized I'd already written what I needed to come next, so the easiest thing just seemed to make the last thing in the method a call to the method I needed.
Second, the lesson on it in chapter 20 of our books was something we had to read along with methods in Chapter 5, so I figured my professor might be impressed if I used it.
Reasonable logic; however, it violates one of the Golden Rules of programming, which has two parts:
1. Do
one thing at a time.
2. When faced with two (or more) choices, or options, for how to proceed: choose the
simplest one first.
Apart from possibly mathematicians - who are trained in things like induction, which help a lot - most people find recursive logic quite hard. I've been at this lark for more than 35 years, and I
still find it tough. Now that's not to say I don't use it; but I always keep plenty of paper and pencils around when I do.
So, faced with your situation, I would have probably written a simple program with a basic loop, and got
that working
first. Then - if I still had time - I would have tried for the brownie points and re-written it as a recursive function (making sure I kept a copy of my "basic" one first of course
).
One thing we have to do is read a program & tell what the outcome will be, & as counter-intuitive as it seems to me as a linguist ... reading a program is much more difficult for me than writing one. Is that normal? It's like I have to write it to understand it...
It's perfectly normal. When you write a program,
you know what you're thinking (hopefully). When you read one, you have to try and reverse-engineer what the
writer was thinking when they wrote it.
And that's just one of the reasons why it's so important to
Write Dumb Code. If I write a program that is hard for other people to read, I've just insured that it will probably be consigned to
File 13 very quickly.
So: write clearly; use descriptive names
everywhere (but within that constraint, keep them as short as possible);
DontWriteLongLines; and stick to
normal Java conventions.
Also: Learn about
Javadoc, and use it.
Everywhere.
And, quite honestly, since I test it as I go along, I sometimes make a small change to see if it will make the program work, & it does, but I'm really not sure why!
I suspect because you still don't understand the problem (or the solution you've written to it). Coding should be the
last thing you do, and ONLY when the process is pretty much a mechanical one. As most of the contributors here are probably bored with hearing me saying:
You cannot write a decent program in Java until to you can describe what it does in English (or your native language).
You might also want to read the
StopCoding (←click→) and
WhatNotHow pages, which exapnd on some of these points.
Good luck. Hope it helps.
Winston