How to Keep Your Code From Destroying You 486
An anonymous reader writes "IBM DeveloperWorks has a few quick tips on how to write maintainable code that won't leech your most valuable resource — time. These six tips on how to write maintainable code are guaranteed to save you time and frustration: one minute spent writing comments can save you an hour of anguish. Bad code gets written all the time. But it doesn't have to be that way. Its time to ask yourself if its time for you to convert to the clean code religion."
The whole article is -1 redundant. (Score:3, Insightful)
I have. It ain't fun. Not that I'm bragging on myself, but I've now had people from the support group stop me in the hall and compliment me on the quality of the code I've written and deployed.
That was just terrible... (Score:5, Insightful)
This looks like it was written for (and BY) freshmen CS majors.
Comment your code smartly? No shit?
Use #defines everywhere? Honestly, I find that having a config file (or DB table) is a lot better, as I can change global variables without even a recompile...
I'm not saying its BAD advice, its just advice that anyone in the real world already knows.
How about something new?
1.) Use test driven development
2.) Write complete unit tests, including bad input
3.) If any piece of code is complex enough to require a comment, make it its own function and comment the function. I believe the only thing that REQUIRES comments are classes and methods. Not pieces of code...
I code go on, but I'm not a writer...
And neither is the author of that pile of trash...
Use a language that checks I/O errors by default (Score:5, Insightful)
C, C++, and Perl are not "safe" in this sense. Python is. Not sure about other common languages.
Re:Who wrote that article? (Score:1, Insightful)
I highly recommend a book called Code Complete. It is kinda pricey and, yes, it is by Microsoft, but I found it to be both helpful and thought provoking.
Mostly agreed (Score:5, Insightful)
Tip 2: Don't use #define. Avoid it as best as you can. Use const int. That's what it's for. It will be typechecked by the compiler, it's much harder to produce bizarre errors, and 99% of the time it's better.
const int NUM_ALIENS_TO_KILL_TO_END_WAVE = 20;
Tip 4: Warning messages don't work. Don't bother with them. Use assert() - if it triggers, your program will crash with a useful error message. Now that's an incentive to make things work!
In my current project, out of 25,000 lines of code, I have almost 1100 asserts. And the first number counts whitespace. Any bugs I have get found and squashed pretty much instantly.
I thought #defines were deprecated in C++ (Score:5, Insightful)
I.e. not
#define PIXEL_WIDTH_OF_PLAY_AREA 800
#define PIXEL_HEIGHT_OF_PLAY_AREA 600
but
const int PIXEL_WIDTH_OF_PLAY_AREA=800;
const int PIXEL_HEIGHT_OF_PLAY_AREA=600;
Invariants (Score:2, Insightful)
The correctness invariants for a data structure can also be embodied in a "sanity_check()" function for that data structure, and also in test cases. But the correctness invariants for an algorithm are rarely embodied in any code anywhere. But they're the ones that give you the programmer an assurance that your code is correct. That's why they're so important.
It was fine... (Score:5, Insightful)
I'm not sure if it really called for a Slashdot entry, but I've been on a few projects with new coders where a quick read of something like this on their parts would have saved everyone a lot of grief.
Re:Use a language that checks I/O errors by defaul (Score:3, Insightful)
Every time you create something, destroy it afterwards.
Assume every action will fail and handle it appropriately.
I have seen 'developers' assume everything will be taken care of, then when the software gets into the users system their usage patterns make it explode.
Simple management needn't make a development time longer or harder and allows you to migrate things to other applications/systems with ease.
Re:That was just terrible... (Score:5, Insightful)
As for your advice
1)Thinking about testing early- good. Writing unit tests-good. The test driven development mentality (write tests instead of design, write unit tests before coding)- bad. It leads to a lot of wasted time, completely rewritten test suites, and throw away work. Thinking about testing early is useful, it may cause you to think about corner cases. But writing them first causes 2 problems- you end up writing the code to solve the tests (rather than solving the problem) and/or you end up throwing away half the test suite in the middle when you refactor the design.
3)Disagree. The purpose of comments is to make sure that maintainers know what the code is trying to do. Anything block of code thats more than 5 or 6 lines deserves a comment. Breaking all of those into independent functions leaves you with hundreds of 5 or 6 line functions, which is even harder to understand how they interact. Frequently the correct thing to do is not break it into a function and just write a 1 line comment.
Obvious and Wrong in One (Score:5, Insightful)
Advice on good comments--great--but really, it's just obvious. Anyone that doesn't get how to comment well doesn't want to comment well. And the above quote made me want to wring his neck. If you don't know the difference between those two operators, you should stick to VB.
Basics (Score:2, Insightful)
Lombardi was known for his comment that if you block and tackle better than the other guy you win.
Magic Johnson was known for being on the court an hour earlier than the other pros and practicing shot after shot.
And Bobby Fisher's guide for beginners is still the best because he knew the basics like nobody else.
Felt I should point out (Score:5, Insightful)
It's not a matter of knowing the difference, it's a matter of the code depending on the difference. If you need to increment beforehand, do it on the previous line. Afterward, do it on the next line. Expressions are like sex: they're better without side-effects.
Some more redundancy, care of Brian Kernighan (Score:5, Insightful)
Re:Mostly agreed (Score:3, Insightful)
I mean, unless you're using K&R C, in which case I feel very sorry for you.
Re:I remember when (Score:1, Insightful)
We end up with so much bloated, broken code because people don't worry about right before 'performance' or 'reusuablity'. Get it right and you'll find a lot of the rest of it comes from that. Including maintainability. The best maintainable code package I worked on also happened to be the fastest(faster by an order of magnitude) over the original. The new code was also object oriented, extensible, clean and actually correct(original didn't accurately calculate a value right).
So I don't think that developers are any different than they used to be. They just write more code that's wrong, bloated and crappy. It just has a prettier interface, more colors when it explodes and more features that never get tested or used.
Re:Who wrote that article? (Score:1, Insightful)
The article may be redundant to many, but I can name at least twenty people off the top of my head taht should give this a long hard read and then read it again.
Re:Who wrote that article? (Score:3, Insightful)
Re:Expected Value (Score:3, Insightful)
Suddenly that "one minute" is a lot of hours spent writing comments that you'll never read, cluttering up your code and getting wronger as you don't maintain them.
If I knew which comment to write, sure, I'd write it. And I do, when I think it's appropriate. There are plenty of times I wish I'd commented something, but they're way outweighed by times I didn't bother. Good function and variables names are more important to me.
If you can't come up with a good name, refactor until you can. A unit of code should do something coherent and easily describable, preferably until you don't need a comment.
Yeah, you'll have to document dependencies, but you should keep them as few as possible. A good language decreases dependencies. I don't have to write "I expect you to free the space for this string" or "This string is stored in a static; do not reuse" because I write in Java.
Re:Who wrote that article? (Score:4, Insightful)
Tip 3 is crap. (Score:3, Insightful)
#define MAX_ALIENS_ON_SCREEN_AT_ONCE 5
I would almost undoubtedly write:
#define MAX_NUM_ALIENS 5
Any confusion caused by the shorter name would be cleared up very quickly, and the shorter name would lead to much more readable code. "
Cleared up very quickly? no, it can only be cleared up after searching your code to realize it is the max number of aliens on the screen, not the max per level, or per game, or whatever the hell you were thinking 2 years ago when you wrote it.
Bad Bad Bad.
sloppy.
Re:That was just terrible... (Score:4, Insightful)
Agreed, but some of the things in this article can be applied conceptually if not literally. Don't want a 2MB config file or header file? Right, me either. But break your program down into smaller pieces and declare stuff at that level and group it together at that level. Conceptually the same as what he is recommending, just done according to your actual implementation.
I too thought the article was very basic, but that doesn't mean that the principles don't apply well to systems larger than a simple game.
Re:That was just terrible... (Score:5, Insightful)
That is just hiding your complexety. A massive tree of functions called each one time is as complex as all the code sequencally in one function. Plowing through the massive tree of functions will cost you more time as reading sequentially through your code whit comments at the places you would have created a function.
Nyh
Re:Who wrote that article? (Score:1, Insightful)
*ahem* (Score:3, Insightful)
Re:Mostly agreed (Score:3, Insightful)
Hungarian Notation (Score:4, Insightful)
I wish he'd included a link to the Wikipedia article on Hungarian notation [wikipedia.org] and specifically referenced "Apps Hungarian". Hungarian notation is essentially a cheap way to create programmer-enforced "types". When these are truly new types ("dirty string", "null-terminated string", etc.) not known to the compiler/interpreter, it might be reasonable; this is "Apps Hungarian". However, prefixing an unsigned int with "ul" (i.e., "Systems Hungarian") is silly; your compiler should warn you/error out if you're trying to do something inappropriate with it, since it knows what an unsigned int is. Hungarian notation will be a useful thing until it's as easy to define new types in common programming languages as it is in, say, Haskell, but it should be used judiciously.
Whipping accountants and CEOs (Score:2, Insightful)
It may be a dead horse to good coders but it is essential that the accounting staff know such things. Such articles can be used to educate them. The articles can also be used to train the newbies they hire.
Unfortunately, there are organizations where the bean counters and CEOs want results NOW and don't want the staff to 'waste' their time on documentation and good coding practices. If you can get your quick and dirty code completed for that 'one time' application up and running really fast, they will love you for it and the effect it has on the bottom line. If you insist that documentation and special good coding refinements are needed and it will take half a day longer, they'll tell you not to waste your time.
Then, a month or a quarter or a year later, they will ask you to take that 'one time' application and modify it for slightly different parameters. And because you did it before, they will expect it to be done in a fraction of the time.
It is an endless treadmill with some organizations. While doing the right thing usually costs less in the long run, getting the results NOW often overrules doing the right thing.
Re:That was just terrible... (Score:5, Insightful)
Re:Use a language that checks I/O errors by defaul (Score:4, Insightful)
True enough, but this misses my point. The question is: What happens when a programmer fails to properly handle errors?
This happens all the time, either because the programmer is not sufficiently competent, or simply misses a check, or because the program in question is a prototype that got pushed into production without being reworked.
Having the language produce useful error messages by default does not preclude an other strategy regarding error handling, resource deallocation, etc. It wouldn't necessarily even need to be done via exceptions. It just needs to change the default strategy from fail-silently to fail-safe, which is what you really want if you care at all about reliability and correctness.
Re:Who wrote that article? (Score:5, Insightful)
That's a bit harsh. Apart from writing comments that are a maintenance liability, using C++ macros when constants would be better, mentioning the use of Hungarian notation that is a liability without mentioning the use that can actually be useful, advocating silent failure in the case of failed preconditions, misquoting Knuth and, to add insult to injury, citing a Wikipedia article in support when that article is currently tagged as having dubious citations (I know; I put the tag there a few weeks ago), failing to understand that games development is one of the few areas where early optimisation is basically a fact of life for some genres, and arguing that you shouldn't rely on programmers knowing basic language facilities like the pre- and post-increment operators in the C family, what was wrong with it? :-)
I am, of course, being facetious. As the author himself points out at the end, much of this stuff isn't obvious to newbies, and it's better if someone tells them earlier rather than later, so kudos to him for taking the time to write it up. I do wish people volunteering such material would get some peer review if they can, though, because the only thing worse for inquisitive newbies than no information is bad information.
Re:Mostly agreed (Score:4, Insightful)
Re:Expected Value (Score:3, Insightful)
Re:Who wrote that article? (Score:2, Insightful)
I have the misfortune of having two trades - photography and graphic/web design/development - and I can say that when I return from a location to pick up coding where I left it three days before, it sometimes takes me several hours to fully comprehend/remember and reconstruct all the already completed processes in my head so I can move forward. Much of the article's seemingly obvious lessons I only learned through time, so perhaps it will save some of the same (and a few headaches) for another just getting into the trade. The coding one.
Re:Comments are a code smell. (Score:4, Insightful)
Re:A Note From the Author (Score:2, Insightful)
But part of the problem I saw when I read your article is that your suggestions really aren't that good. Take for instance your example of "good" comments:
That comment is actually documentation, and if you are going to document in comments (not *entirely* a bad idea) then you should be actually using a type of comment designed to be picked up by some documentation system, such as autodoc.
Describing what your code does is the job of documentation, describing why your code does what it does the WAY it does is the job of comments.
An example of just saying what you're doing instead of why you're doing what you're doing.
Why do we need to say that this changes the bullets position?
Shouldn't the code probably look like, bullet.setX(x); bullet.setY(y); or some variation thereof and a redraw? Wouldn't that indicate that the code is moving the bullet? Do we really need a comment to say this?
In retrospect, a good time to use a comment is when you deviate from anything a future onlooker would be expecting from your method, function or subroutine. For instance, where you would do something specifically because of another bug that or behavior that is out of your control.
A smart person doesn't need to remind himself what code X does, unless it's not obvious.
In the section where you suggest using define a lot, I honestly consider that a particularly bad idea. Using global constants is just in general a bad practice. A good practice, on the other hand, is having all arbitrary static data be a matter of configuration. That is, instead of defining NUM_ALIENS_TO_KILL_TO_END_WAVE as a compile time constant, or any other form of literal, define it in a configuration file so it can easily be modified without a code change.
Enabling behavioral changes without code changes is critical to software success. Every time you change code, you rebuild and redeploy things. And this provides the potential for other
MOD PARENT UP (Score:2, Insightful)