In this post, I’m going to give you advice that I am nearly sure you will ignore. The reason I know this is because most people I’ve given this advice to, I’m nearly sure, ignored it. I doubly know this because it took me years—nay, maybe over a decade—for me to start listening to this advice. So, believe me, I won’t be offended if you ignore this advice.
But I’m going to give you the advice because it really is good advice and, if you listen to it, even if you don’t want to, it will save you an enormous amount of frustration. Like truckloads. Semi, tractor-trailer loads.
So, here’s the advice: Do not write more than 2 lines of code without testing to see that you get the result that you’re looking for. You test your result by writing the result out to the screen. When you’re more experienced, you can bump that to 5 lines of code, but for now, stick to 2.
That’s it. So, why? Simple: if you write more than 2 lines of code, and you get an error, it will be much harder to figure out why the error happened. When you write only 2 lines of code, you can much more quickly isolate where the error is and fix it.
The difficulty of figuring out what your error is increases exponentially with more lines of code. This is both because we have more places to check and we have more kinds of code that we’ve written, which opens us up to more kinds of errors that can occur, but this is also because when you have multiple lines of code, they can interact with each other in ways you cannot predict and do not expect. Computers are not smart. They are dumb. Dumber than bricks. Dumber than bricks made of sand, because that’s what they are, bricks made of sand. They will take perfectly intelligent code and munge them up in their own crazy way. When you write code, you need to do everything you can prevent the computer from having too much to work with.
So, what if you don’t follow this advice? You’ve written 100 lines of code and it’s not working. What do you do? Here are some thoughts:
- Start from the beginning of your program and comment out everything besides the first two lines of code. That includes the lines of code you’ve written after the first two lines. But, you say, why would the lines after affect the first two lines? Who knows? Remember, the computer is not smart! It shouldn’t have any effect, but weird things happen; comment the lines out and you won’t have to worry about it.
- Did you write out the results you expect? Do so, using a
- If even the first two lines of code do not work, and you cannot figure out the error, comment out even those two lines and type in one line you know will work (for instance, a
Again, just write two lines of code at a time! You’ll be more sane and your mother will thank me! 🙂