Beta

Slashdot: News for Nerds

×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Code Reading: The Open Source Perspective

timothy posted more than 9 years ago | from the because-that's-the-code-you-can-read dept.

Programming 464

nazarijo writes "You can usually tell someone who's been writing a lot of code by how they write code. That may sound like a tautology, but it's got a deeper meaning than that. What editor they use, what idioms they use to avoid common pitfalls, and what organization patterns they employ all tell you what kind of programmer you're meeting. When you first start writing code, so many things are inconsistent and just plain wrong that it's almost embarrassing. I know that when I look over older code that I've written I feel sheepish about it. But how do you grow as a programmer, and what really makes a good programmer beyond language familiarity?" Read on for Nazario's review of Code Reading: The Open Source Perspective, a book which attempts to instill deeper knowledge about programming than just "knowing how."

A few books are tackling this subject, including Coder to Developer and Programming Language Pragmatics. These books don't teach you much about a particular language in the way that an introductory text would. Instead, you grow as a skilled developer by studying them and learning from them. That's one of the key things that people are talking about lately, that to be a strong developer requires more than a working knowledge of a language. It requires a familiarity with the strengths, weaknesses, and core features of a language and the base libraries to be efficient.

Code Reading: The Open Source Perspective is one of these books in this small but growing library. In it, Diomidis Spinellis takes you through a large body of code and focuses on several languages, techniques, and facets of development that differentiate strong developers from weak ones. What I like about this book is how much it covers, how practical the information is, and how much Spinellis teaches you. You wont learn a language, which is the complaint of some people who read this book, but if you know one or two you'll be a better programmer.

Perhaps one of the most telling things about the book is that it draws heavily from NetBSD source code, and features over 600 examples to make the point. Examples are often annotated using NetBSD as a reference. This makes sense, because NetBSD is a large project that's relatively stable and mature. Everything from how to define a C structure consistently and sanely to UML diagrams and build systems are covered, making this truly a developer's book. However, even Windows and Mac OS X developers will benefit, despite the BSD focus.

Chapter 1 introduces some of the basic tenets of the book, namely that code is literature and should be read as such. All too often people only read code when they have a specific problem to solve or want to get an example of an API. Instead, if you read code frequently you'll always be learning things and improving your skills. Also, Spinellis discusses the lifecycle of code (including its genesis, maintenance, and reuse), which simply must be taken into account if code is to be good. Poorly skilled developers forget these things and just slap it together, never thinking ahead.

In Chapter 2, a number of concepts basic to any programming language are covered, including the basic flow-control units common to many languages. The book focuses on C, with additional coverage given using C++, Java, and a few other things thrown in for good measure. As such, these chapters -- in fact the whole book -- focuses on concepts common to these languages but absent in some other languages, like Scheme or LISP. One neat section is called "refactoring in the small." It illustrates the real value of the book nicely, in showing you various ways to organize your code and your thoughts for various effects. Oftentimes a book will only teach you one way (which doesn't always suit your needs), and Spinellis' examples do a nice job of escaping that trap, not just here but throughout the book.

Chapter 3, "Advanced C Data Types," focuses on some language-specific matters. These are pointers, structures, unions and dynamic memory allocation, things that most people who code in C may use but only some truly understand well. Again, a somewhat basic chapter, but useful nonetheless. Make sure you read it; chances are you'll learn a thing or two.

In Chapter 4, some basic data structures (vectors, matrices, stacks, queues, maps and hash tables, sets, lists, trees and graphs) are covered. This is an important chapter since it helps you see these structure in real-world use and also helps you understand when to chose one structure over another. While Knuth, CLRS, or other algorithms and data structures texts cover these, they often do so in isolation and at a theoretical level. While their coverage is short, it's to the point and usable by anyone with a modest understanding of C.

Chapter 5, "Advanced Control Flow," the last chapter that deals with actual programming information, is another useful one. Again, short but to the point, this chapter covers things like recursion, exceptions, parallelism, and signals, all topics that have warranted their own books (or major sections in other books) but which are covered in a single chapter here. Still, seeing them side-by-side and in the context of each other and in real-world use provides some justification for the compact presentation.

The remaining chapters of the book go well beyond a normal programming book and focus on projects. These chapters complement the first bunch nicely by focusing on the organization of your code and projects. Chapter 6 deals specifically with many of the commonly identified (but rarely taught) things like design techniques, project organization, build processes, revision control, and testing. A number of things that aren't covered include defining and managing requirements for a release and their specifications, basics on how to use autoconf and automake, and instead rips through a whole slew of topics quite quickly.

Chapter 7 is sure to be controversial for some people: it covers "Coding Standards and Conventions." Some people seem to be big fans of the "if it feels good, do it" style of programming, and instead of writing sane, usable code, what they produce is buggy and messy. This chapter teaches you tried and tested methods of naming files, indentation (and how to do so consistently using your editor to help), formatting, naming conventions (for variables, functions, and classes), as well as standards and processes. The style and standards are (as you would expect) based on NetBSD, which differ slightly from GNU and Linux standards, as well as commonly found Windows practices. However, I think you'll agree that the style is readable with minimal effort, and that goal, coupled to consistency, is paramount in any standard.

Chapter 8 introduces you to documentation, including the use of man pages, Doxygen, revision histories, and the like. Also included are hints at using diagrams for added value. One thing I don't like about this chapter is the opening quote, which sets a bad precedent. It blithely suggests that bad documentation is better than none, which is highly questionable. Misleading docs can be worse than no docs at all, since someone without docs will have to dig through the code in front of them to understand it. Someone with bad docs will rely on the docs and wonder what's broken when things go awry.

Chapter 9 focuses on code architecture, such as class hierarchies, module organization, and even core features like frameworks to chose. This chapter covers a lot of material, and is, despite its size, simply too terse on many of these subjects. It serves as a decent introduction, but doesn't go very far in some places, considering the importance of the material. However, like much of the book, it's a good introduction to the topics at hand.

Chapter 10 also features a lot of good things to know. Granted, you could pick them all up with a lot of hard work and scouring for information, but it's easier to have them presented to you in a cohesive format. The chapter discusses code reading tools, things that you use to help you dig around a large body of code. One you get over a few source files, even if you have well-organized code and interfaces, many changes can require that you inspect the data path. You can do this manually, or you can be assisted with tools. Tools like regular expressions, grep, your editor -- Spinellis shows you how to make use of all of them when you write code. A lot of tools I've never used (but have heard about) are featured, and their use is demonstrated, but of course many tools are simply ignored, focusing on popular ones that will work for most people.

Finally, all of the above is brought together in Chapter 11, "A Complete Example." A small tour of a large, complex piece of code is taken (34,000 lines of Java) as the author makes changes. It's unfortunately in Java, when so much of the book focused on C (why couldn't they have been consistent examples?), but it works. The example itself could have covered a few more things, such as a proper JUnit example, but overall I'm pleased with it.

Overall, Code Reading: The Open Source Perspective is ambitious and worthwhile, both as a complement to a bookshelf of study that includes The Practice of Programming and Design Patterns, and to someone who is growing tired of books on learning a language. At times it feels like the author promised more than he wound up delivering, but it serves as an introduction to a large number of topics. You wont learn a language, and you wont be able to get as much out of the book if you don't engage it with practice, but it's a useful book to get started on the road from being someone who knows a language or two to someone who is a developer, ready to contribute to a team and work on large projects. Never underestimate the skills required to be a good developer, because they go well beyond knowing how to use a language.


You can purchase Code Reading: The Open Source Perspective from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

cancel ×

464 comments

Consistency and good comments (4, Insightful)

Neil Blender (555885) | more than 9 years ago | (#11882113)

When I see that develop in someone, then I know they are going to the next level. When I don't see it after time, I know they will never evolve.

Re:Consistency and good comments (5, Interesting)

Arimatheus (779497) | more than 9 years ago | (#11882478)

Pseudocode.

The other day I was looking at some code a peer of mine wrote and noticed a few places where there were comments with no code associated with them, he (like me and I'm sure a few others) builds the frame of his project and then fills in the code. I think it really helps to think the project through before hand, build your comments and then write.

And oddly, you'll notice that a lot of the coders who do this know a large multitude of languages and probably developed this habit over the course of doing personal projects, it helps you quantifiably say how far along you are in the project, remember what direction you were taking with the project (because of course we NEVER let there go a ~3 week gap in personal projects :-P ) and allows you to look at the fundabmentals of a project without forcing yourself into a language before you can address where your language of choice might fail.

At least that's the way I see it.

Re:Consistency and good comments (1)

Lunix Torvalds (866066) | more than 9 years ago | (#11882511)

I would like to see more comments in the new code coming in from the contributors. Watch out for an announcement concerning this on the mailing lists.

Re:Consistency and good comments (0)

Anonymous Coward | more than 9 years ago | (#11882543)

dewd WTF?!?! Linus, is that realy you?!?

read my lips (-1, Offtopic)

Anonymous Coward | more than 9 years ago | (#11882119)

first post

Re:read my lips (-1, Offtopic)

Anonymous Coward | more than 9 years ago | (#11882148)

Or...NOT!

I don't understand (1, Funny)

AntiPasto (168263) | more than 9 years ago | (#11882132)

... you're saying that there's more to it than just getting it done?

Re:I don't understand (3, Insightful)

cperciva (102828) | more than 9 years ago | (#11882196)

... you're saying that there's more to it than just getting it done?

Yes. Getting it done right.

Re:I don't understand (2, Funny)

nacturation (646836) | more than 9 years ago | (#11882304)

Ah, grasshopper... your code may get things done, but will someone in Soviet Russia who has to parse through your unreadable code get done by it?

Re:I don't understand (0, Troll)

Thud457 (234763) | more than 9 years ago | (#11882381)

Actually, it's usually the other case. Management outsources the development of new modules to vodka-addled Russkis, and honest, tax-paying Americans get the thankless job of hacking through 3,364,283 lines of multi-layered macros in 192 modules to learn that it prints "! ".

Re:I don't understand (0)

Anonymous Coward | more than 9 years ago | (#11882396)

Stupid fucking slashdot ate my mad 'leet Russian. Bitches.

Re:I don't understand (1)

BattleCat (244240) | more than 9 years ago | (#11882484)

No. Your leet Russian was outsourced to Russia :-) And was buried somewhere in the countless layers of vodka labels and /insert your typical Russia stereotype here/

HAHAHAH! Everybody's an idiot but me! (1)

Thud457 (234763) | more than 9 years ago | (#11882556)

Don't get me started about projects architechted by interns and implemented [slashdot.com] by highschool dropouts!

Re:I don't understand (2, Interesting)

TheSpoom (715771) | more than 9 years ago | (#11882580)

Damn right. My new job involves making modifications to a Russian-developed PHP shopping cart, and while it's decently programmed in some places, others are *hellish* to try to work through and/or edit. /me keeps telling himself that it's all for the experience... ;^)

Re:I don't understand (0)

Anonymous Coward | more than 9 years ago | (#11882380)

I tend to jump in there with only a few commands that I know how to use, and see if I can cobble together a script that does what I want.

No, it is not professional, by any means, but I work for myself, not anyone else, so I tend to want to accomplish something, and try and use a script or a series of them to get things done. If it works, I use it.

The coding is not so much the issue, as the overall design of the project.

I'm sure a professionally trained coder could redo a lot of my stuff, and have marvelous results.

I maintain this Knoppix remaster [geocities.com] , and one of the things I have in there is a way to switch mouse cursor themes, there are 4 of them in all, with one having three variants.

I got a lot of negative feedback from beta testers in the beginning about the default Knoppix 3.4 mouse cursor, being too small, especially for laptops. I fixed that, and now can focus on other problems. (There are always other problems...)

Very true. (3, Insightful)

gimpynerd (864361) | more than 9 years ago | (#11882138)

This is very true. While learning a certain language I always have many inconsistanies in my code. In fact I always want to go back and change it as I progress. It just shows that experince is much more than talent.

Re:Very true. (5, Insightful)

superpulpsicle (533373) | more than 9 years ago | (#11882214)

Personally I hate wasting time writing a function to do something only to find out 10 days later... the language already comes with a library that does the exact same thing. Experience do count there.

Cookie-cutter book? (-1, Flamebait)

Anonymous Coward | more than 9 years ago | (#11882142)

Throw "open source" in the title. It'l l sell like hotcakes!

Re:Cookie-cutter book? (1, Insightful)

Anonymous Coward | more than 9 years ago | (#11882249)

Actually, the parent is neither off-topic nor flamebait. This book can be very good (and I think I'll buy it if I can) but this reviews lacked a comparison with another "Bibles" such as "Code Complete" (a Microsoft Press book!). Code Complete was to me the book that gave me another level of programming, exactly like this "Open Source Code Complete". The problem is really with the word "open source embedded in the title...

Blogging entails responsibilities... (0, Flamebait)

queef_latina (847562) | more than 9 years ago | (#11882145)

Remember that dell commercial, where the techie is whispering to the camera in front of a disassembled laptop?

You're that guy.

You might look at the douchebag boss with the coffee cup with disdain, as I do, but remember that he's the one fucking you in the ass, and the world always sides with the guy on top, as I do.

While I think it's cute that you think linux will be a viable desktop or that game designers actually pay attention to your concerns, I believe the time has come for you to ask yourselves why you've been involuntarily celibate for these last seventeen months. Because your urge to force computer preferences on the rest of the world is symptomatic of all that is broken with your personalities.

Microsoft is guilty of the same crime of trying to force their technology on the population, but they have money, and power, and many of them possess social skills requisite to being in big business. Linux fanatics on the other hand try to pull this and fall flat on their faces, because they aren't rich, they have no power, and their social skills prompt them to cry themselves to sleep in dark lonely corners.

Remember nerds- the rest of the world is that douchebag with the coffee cup, disapproving and scolding when you overstep your bounds. We might not lend ourselves well to sympathetic portrals in commercials and other media, but every night we can come home in a shiny expensive car, to a nice furnished apartment, and eat some pussy before going to bed. Our lives revolve around windsurfing or skiing with friends that you don't have, and some unfaithful extramarital sex on the side.

We laugh at you because you're different, you laugh at us because there's nothing else you can do.

Whenever I lay off employees, I always use pink slips. Last time I did it in person, I almost bit my tongue off trying to keep a straight face. Trust me, I don't remember you at all.

I love my job

I hear The Home Depot is hiring.

Seriously linux users, you're operating system wont make up for the fact that girls are repulsed by your bodies.

Re:Blogging entails responsibilities... (1)

dj_cel (744926) | more than 9 years ago | (#11882492)

Before everyone goes into a tirade about the parent comment, I will point out a couple things. He is right in one sense, they laugh because we are different. I think it's funny to them that you could actually have a philanthropic attitude about something and produce because you like it, like art. I think programming requires a certain ammount of skill, and to do it correctly and efficiently is an artform of sorts. Posts like these are the only recourse against an army of those who have beyond the skill necessary to do the job. Yes sir, enjoy your "shiny car" and the hooker you apparently go home to everynight. It won't last forever. Besides that, it's funny about this outsourcing thing you know, because you might find yourself with a pink notice.

comments (5, Insightful)

PoopJuggler (688445) | more than 9 years ago | (#11882147)

You can tell a great deal about the maturity of a programmer by the quantity, and quality, of comments.

other important thing about comments (1)

queef_latina (847562) | more than 9 years ago | (#11882173)

Remember that dell commercial, where the techie is whispering to the camera in front of a disassembled laptop?

You're that guy.

You might look at the douchebag boss with the coffee cup with disdain, as I do, but remember that he's the one fucking you in the ass, and the world always sides with the guy on top, as I do.

While I think it's cute that you think linux will be a viable desktop or that game designers actually pay attention to your concerns, I believe the time has come for you to ask yourselves why you've been involuntarily celibate for these last seventeen months. Because your urge to force computer preferences on the rest of the world is symptomatic of all that is broken with your personalities.

Microsoft is guilty of the same crime of trying to force their technology on the population, but they have money, and power, and many of them possess social skills requisite to being in big business. Linux fanatics on the other hand try to pull this and fall flat on their faces, because they aren't rich, they have no power, and their social skills prompt them to cry themselves to sleep in dark lonely corners.

Remember nerds- the rest of the world is that douchebag with the coffee cup, disapproving and scolding when you overstep your bounds. We might not lend ourselves well to sympathetic portrals in commercials and other media, but every night we can come home in a shiny expensive car, to a nice furnished apartment, and eat some pussy before going to bed. Our lives revolve around windsurfing or skiing with friends that you don't have, and some unfaithful extramarital sex on the side.

We laugh at you because you're different, you laugh at us because there's nothing else you can do.

Whenever I lay off employees, I always use pink slips. Last time I did it in person, I almost bit my tongue off trying to keep a straight face. Trust me, I don't remember you at all.

I love my job

I hear The Home Depot is hiring.

Seriously linux users, you're operating system wont make up for the fact that girls are repulsed by your bodies.

Re:comments (5, Funny)

Rosco P. Coltrane (209368) | more than 9 years ago | (#11882184)

Funny, my colleague posted many good comments here while on the job and he finally got sacked...

Re:comments (1)

EvanED (569694) | more than 9 years ago | (#11882525)

Hey, your parent didn't say what the indication was, only that it was an indication ;-)

Re:comments (4, Insightful)

Suicyco (88284) | more than 9 years ago | (#11882203)

This is absolutely true. The more you have worked on past software, horrible code, etc. the more you value proper commenting and documentation. Hence, the higher quality you produce, with full knowledge that it WILL be useful someday. Many times I spend just as much time carefully crafting comments and documentation, formatting the code, etc. so it reads as cleanly as possible.

I suppose it also holds that once you have surpassed the threshold of super-duper quality commenting, you get to the point of such awesome code that it documents itself, so you come full circle.

Re:comments (2, Interesting)

nkh (750837) | more than 9 years ago | (#11882286)

with full knowledge that it WILL be useful someday.

That's why you need Literate Programming! [stanford.edu] A very good book for all the family ;)

Use comments only when needed (5, Insightful)

c0d3r (156687) | more than 9 years ago | (#11882225)

I disagree when writing Java and C#. These languages are inherintley readable if you write clean, understandable code with good variable names. Comments should be used whey you implement something that you can't understand by reading the code. Its quickker for me to read clean code, and comments often get in the way and get outdated and hurt more than they help. Maintainance is the Iceburg.

Re:Use comments only when needed (3, Insightful)

enjo13 (444114) | more than 9 years ago | (#11882299)

You couldn't be more correct. Comments are often to blame for maintainibility problems, as dangling comments can absolutely destroy the readibility of code.

I do beleive you can judge a programmer by the quality and quantity of comments.. A good programmer comments only when the code NEEDS commenting. No more, no less.

Re:Use comments only when needed (1, Interesting)

Anonymous Coward | more than 9 years ago | (#11882303)

One big reason for putting in comments is to define what your doing at that step in the code. Often having the comment followed by readble code helps catch logic errors and make it easier for someone less familiar with the language, libraries, or the project involved. This also means, the comments need to address the concept involved, not just saying in text what the code does.

For example, don't say /* increment i by 1 */ when /* advance to the next record */ is conceptually better.

Re:Use comments only when needed (5, Insightful)

Anonymous Coward | more than 9 years ago | (#11882343)

Just because it's obvious what your code is doing doesn't mean it's obvious why it's doing it. Commenting is still important.

Comments need structure (3, Informative)

yintercept (517362) | more than 9 years ago | (#11882401)

It seems to me that documation needs a structure. Structures like records of revision and design documents are useful. Free form comments in the code turn into white noise. Since I am far more interested in what a piece of code does, I pretty much ignore all documentation in the code. It seems like the majority of documentation in code becomes obsolete as people modify the code. For example, if a person has a problematic part in their code, they add copious notes document. When the problem finally clarifies in their mind and the find the code, they end up leaving obsolete documentation that just confuses people at a later date.

Personally, I think a person should document the interface, maintain a record of revision. The code itself should only be documented when the code is doing something out of the ordinary.

So, when I am learning a language, I put a great deal of notes in the code. As I learn the typical flow of the programs, I write less documentation in the code. When I have a strong feel for the language and reading the code is more informative than reading notes, my notes all but disappear. I've noticed many other programmers seem to have the same tendency. They write less documentation in code and they learn the language.

Having supported a large number of applications. I greatly appreciate good design documention, but discard notes in the code.

Re:Use comments only when needed (4, Insightful)

Viking Coder (102287) | more than 9 years ago | (#11882529)

Sure - everything works great if you are fortunate enough to start with clean code, and keep your code clean.

But the rest of us work for a living. You know, for bosses who don't "Get It." =) We have to fight for the time to keep code clean, because that time could be spent adding features instead. It can be a hard battle.

When you're in that kind of environment, comments can save your life. Or at least your ass.

Re:Use comments only when needed (3, Insightful)

14erCleaner (745600) | more than 9 years ago | (#11882548)

Its quickker for me to read clean code

Maintainance is the Iceburg.

It's really hard for me to nitpick spelling, but I can't help myself, so please forgive me...

A good first step in writing clean, maintainable code is to be self-aware. Many experienced programmers don't realize that they write crappy code. Honest code reviews can help, but most people don't take criticism well, and negative style comments are ignored.

(Of course, my code is perfect... :)

Re:Use comments only when needed (4, Insightful)

AuMatar (183847) | more than 9 years ago | (#11882582)

Whats clear to you isn't clear to me, and vice versa. Whats clear to you now won't be clear to you in 6 months, much less 12. Thats why comments are good- in 6-12 months you will understand the comment, while you might not the code. And a thrid party is far more likely to get the comment than the code.

As for comments getting outdated- thats why you update comments when you update code. If you don't do that, you're a poor programmer. Changing the code and not the comment is doing half the job.

Re:comments (3, Insightful)

Mumpsman (836490) | more than 9 years ago | (#11882266)

Actually, what you can tell about a programmer from comments is the ability and understanding of his/her direct supervisor.
Understanding the value of good code is one thing, but insulating your developers from top-down pressure and unreasonable deadlines which force them to "slap it together" allows programmers to prosper.
If your shop is producing crap code it's because your management is crap.

MOD PARENT UP (2, Interesting)

guitaristx (791223) | more than 9 years ago | (#11882357)

Believe me, this is ever so often the truth. I can't count the number of times where I thought "WTF was this programmer thinking?" while maintaining legacy code, only to find out that the offending code, after tracing through the authors and check-in logs, was driven solely by a manager cracking the whip for a quick-and-dirty solution.

What about COBOL? (2, Funny)

HeighYew (840686) | more than 9 years ago | (#11882388)

I write COBOL code. Since COBOL is just like writing in English, why should I need to comment?

... on second thought...

Hooray for self-documenting code!!! :)

Literature (4, Funny)

14erCleaner (745600) | more than 9 years ago | (#11882155)

Chapter 1 introduces some of the basic tenets of the book, namely that code is literature and should be read as such.

Unfortunately, some experienced programmers write like ee cummings, and others like avant-guard poets.

Re:Literature (4, Funny)

Geoffreyerffoeg (729040) | more than 9 years ago | (#11882321)

HRESULT hReply = authEECummings (atTheLeast) vhlpDidNot vrbUse adjHungarian nNotation;

Hmm not sure (4, Funny)

Rosco P. Coltrane (209368) | more than 9 years ago | (#11882158)

You can usually tell someone who's been writing a lot of code by how they write code.

I looked at the slashcode once and I'm fairly sure Taco worked on debugging serial port line noise before starting /.

WHEN THE SHIT HITS THE FANS (-1, Offtopic)

Anonymous Coward | more than 9 years ago | (#11882167)

WHEN THE SHIT HITS THE FANS
in a sluggish economy inflation, recession hits the land of the free standing in unemployment lines blame the government for hard time we just get by however we can we all gotta duck when the shit hits the fan

10 kids in a cadillac stand in lines for welfare checks let's all leach off the state gee!the money's really great! soup lines free loaves of bread 5lb blocks of cheese bags of groceries social security has run out on you and me we do whatever we can gotta duck when the shit hits the fan

Comments (5, Insightful)

The Amazing Fish Boy (863897) | more than 9 years ago | (#11882178)

The amount of comments in code is interesting. It kind of starts at an extreme, then moves slowly to the middle, happy land.

If you started programming, you either chose to comment a lot, or not at all. "A lot", because you were never sure what your code was doing, and always needed the reference. Or "not at all", because you could make sense of the code very well.

Then you start your first big project. For the big commenter, he realizes after getting quite a bit of work done that a lot of time was "wasted" on comments. ("// This line increments the 'i' variable by 1".) Further, these comments seem way too obvious. For the non commenter, they get lost easily and wish they commented more.

So it goes in the opposite direction from when it started. The big commenter comments way less, and the non commenter comments way more.

Then it repeats. Eventually the programmer gets the happy medium of the right amount of comments.

This has been my experience, in my own code, and checking other people's code. Thoughts?

Re:Comments (1)

dakara (798841) | more than 9 years ago | (#11882262)

Let me guess... you're part of the "big commenter" crowd? :-)

Re:Comments (0)

Anonymous Coward | more than 9 years ago | (#11882521)

Big comment bad.

Re:Comments (1)

Feneric (765069) | more than 9 years ago | (#11882293)

Yes, when I first started coding I used a lot more comments than I do now. In time one realizes that comments can get out of date, too, and need to be maintained as much as the code...

Now I make heavier use of expressive names for variables, classes, and methods, and tend to focus comments on interfaces and particularly tricky bits of logic.

It's a pity there hasn't been more work with Literate Programming out in the world at large...

Re:Comments (0)

Anonymous Coward | more than 9 years ago | (#11882516)

I remember the first thing that my CS instructor said... comment everything.

So I did

#include // Add the headers for text output

main() // The main function
{ // Begin main function
cout "Hello World!"; // Will print "Hello World!"
return 0; // Does not return an error
} // End main function

Re:Comments (2, Insightful)

jallen02 (124384) | more than 9 years ago | (#11882567)

It all really depends. Ultimately I feel that you will learn to write code that explains itself to a large degree. There are two times I ask them to make comments.

1.) The first time to comment is when you are doing something you know are not standard. Bitwise shifts to multiply, things you know are sub-optimal etc. Exceptional things that are not done how they shold be done, or are typically done.

2.) When you want to explain how a relatively large block of code is working, or an entire classes purposes. Explaining a method or a class. Or a block of code to give an idea of flow.

Another thing that I feel improves comment quality is to force them to be complete sentences. Try and keep the sentences brief and complete so that it clearly illustrates what you are trying to say without repeating. The "Do not Repeat Yourself" DRY principle applies to written communication as well as code.

If you always refer back to these simple rules you will generally have code that is easier to maintain and that the comments don't go out of date on as quickly. I really think you could write an entire book on commenting code and naming variables and organizing code flow. Good Luck and happy coding!

I will agree that developers go through phases in how and when they comment, but having someone lay out guidelines and telling you when to comment and giving you a few concerete examples makes a huge difference. For me its always about being a good leader and doing what I say. I have seen programmers come from mediocre/average just following a few simple "rules". Commenting is a huge part of it. Because if you can comment at an abstract/high level you can prove you know what the code should be doing. And if you write comments before you write the code.... ;-)

Jeremy

hmm... (0)

CynicalGuy (866115) | more than 9 years ago | (#11882186)

If you know how to code, you don't need this book!

On the topic (2, Funny)

advb89 (841436) | more than 9 years ago | (#11882202)

Speaking of which, I was recently browsing sourceforge [sourceforge.net] , and happened to notice this project which MUST be a good one since its home page has an error screen:

Fatal error: Cannot redeclare fecha2mysql() in /home/groups/c/cp/cphp/htdocs/funciones.php on line 4

Not to mention they misspelled 'functions'!
This project can be found here [sourceforge.net] , and there homepage here [sourceforge.net] .
Oh yeah, if you happen to be reading this, agustindondo, no offense intended :)

Re:On the topic (1)

yoink00 (819648) | more than 9 years ago | (#11882252)

Just because you speak English that doesn't mean it's the only language in existance... I think you'll find funciones is Spanish. Stu

Re:On the topic (1)

advb89 (841436) | more than 9 years ago | (#11882316)

Leave me alone, i've got a c++ in my spanish 1 class. Wise you are!! (see, i can barely speak english)

Re:On the topic (1)

krunk7 (748055) | more than 9 years ago | (#11882265)

Not if they're spanish they didn't:
Spanish Dictionary [spanishdict.com]

Re:On the topic (1)

cfsmp3 (774544) | more than 9 years ago | (#11882270)

funciones.php = functions.php (in Spanish)

You're a bit dumb, aren't ya...

Re:On the topic (1)

advb89 (841436) | more than 9 years ago | (#11882347)

Unfortunatly as i mentioned before i have a c++ in spanish 1 (yes i said spanish 1). But that still brings me back to the point that a php board project has an error in the first place (on their own web page)

Re:On the topic (2, Funny)

javaxman (705658) | more than 9 years ago | (#11882491)

Unfortunatly as i mentioned before i have a c++ in spanish

See, and here I was giving you the benefit of the doubt and thinking you were either being funny or trolling, but... well, unfortunatly you were just being dense. I hope you check your spelling in your own code better than you checked it in that last post, eh? Now I'm back to thinking you're funny again... if not intentionally.

Re:On the topic (1)

patri26281 (246991) | more than 9 years ago | (#11882281)

It's spelled correctly. Funciones is spanish for functions in english. :-)

Re:On the topic (1)

mpupu (750408) | more than 9 years ago | (#11882315)

Not to mention they misspelled 'functions'!

They just seem to be using a different language. In Spanish, fecha = date and funciones = functions.
Agustin is also a Spanish name.

Re:On the topic (0)

Anonymous Coward | more than 9 years ago | (#11882325)

Very funny: the SQL code has variables named in spanish (or some funny language) and everything is hard-coded (the worst thing you could do for modularity!)

Re:On the topic (2, Informative)

Jason Ford (635431) | more than 9 years ago | (#11882369)

Hmmm, it could be that agustindondo is a Spanish speaker. 'Funciones' is Spanish for, you guessed it, 'functions.' Oh, and 'fecha' is 'date' en español.

Re:On the topic (1)

YellowElf (445681) | more than 9 years ago | (#11882371)

And "fecha" means date...

Re:On the topic (1)

daremonai (859175) | more than 9 years ago | (#11882429)

Not to mention they misspelled 'functions'!
Well... only if you consider Spanish to be misspelled English.

Re:On the topic (1)

molecular (311632) | more than 9 years ago | (#11882497)

I think "funciones" might be espanol, portuges, italiano or something. so maybe it's not mispelled?

Althought I object to localizing variable-names and such myself, you should acknowledge some people might feel more comfortable naming stuff in their native tongue. It tends to sound a little queer combined with the english keywords of the language itself:
while (weitermachen) { tu_es(); }
I am currently getting into a rather large navision-based database project. There, you have localized names for the database objects. In the code, you can use (in this project) either the english or german names. What a mess! I think this started when microsoft bought navision :)

Experience (2, Funny)

kent, knower of all (47897) | more than 9 years ago | (#11882208)

So the bottom line is experience? Then the following holds:

Bad Code + Bad Code + Bad Code = Good Code!

Yeah, right.

--

Select * from users where clue > 0
0 rows selected

I believe that what you are trying to say is that: (3, Insightful)

adolfojp (730818) | more than 9 years ago | (#11882221)

The smart man learns from his mistakes ...

... but the wise man learns from other peoples mistakes.

I guess that I am just kind of average :-P.

Cheers,
Adolfo

Re:I believe that what you are trying to say is th (0)

Anonymous Coward | more than 9 years ago | (#11882469)

so, everyone who makes mistakes is a teacher to some?

Re:I believe that what you are trying to say is th (1)

adolfojp (730818) | more than 9 years ago | (#11882575)

Wait... let me write that down :-).

Get an account AC and harvest some karma.

Cheers,
Adolfo

So that is why my speling and gramor is so bad.... (1, Funny)

Omega1045 (584264) | more than 9 years ago | (#11882231)

I am waiting for the intelliSense to suggest the word!

Re:So that is why my speling and gramor is so bad. (0)

Anonymous Coward | more than 9 years ago | (#11882540)

I am waiting for the intelliSense to suggest the word!

Not exactly classic flamebait. I'm trying to get incensed by the comment but it isn't working for me. I guess that's why I'm not a moderator.

Coding style (5, Insightful)

tjwhaynes (114792) | more than 9 years ago | (#11882241)

After a while working on very large projects (>1Gb source code) I've begun to find that certain things which looked fine for personal projects are serious problems when you scale up.

Most critical is managing complexity. Large, complex functions are bad - they have more bugs, they are harder to maintain, harder to bug fix (a change has more likelyhood of breaking something else). If a function has grown beyond a hundred lines of (real) code, it is almost certainly too large. If it has more than 4 levels of nesting, it is too large.

Comments also matter. It's easy to code a couple of thousand lines of fresh code over a weekend if you get in the groove. It is almost impossible to unpick it one year later if you didn't comment it as you go.

Variable and function names should be expressive. No single letter variable names! No obscure combinations of letters like words with no vowels (fnct could be function or function control, or even Function Numerical Constant Type). And personally I find that reverse Hungarian notation can be more trouble than it's worth. puiAnnoying!

Build in automatic checks on everything. If a pointer to a function should never be null, check it and stop if it is. If a variable should only have values 1 -> maxIterations, then check it. If you (or anyone else) ever breaks that assumption, the code will flag it for you.

Beyond that, nothing beats good design, especially designs where extending the original work is easy. So many designs end up as tangle knots of conflicts because they ended up trying to solve problems that the original code base never envisaged.

Cheers,
Toby Haynes

Re:Coding style (1)

nacturation (646836) | more than 9 years ago | (#11882370)

Judging from your sig, I take it you work for IBM. Out of curiosity, what projects had more than a gigabyte of source code? That's just massive! (To me, anyway.)

Re:Coding style (4, Insightful)

excesspwr (218183) | more than 9 years ago | (#11882466)

You point out some very common problems my colleagues and myself have run into and discussed many times.

Just to add some more to what you are stating. I've come to the realization that I must determine the final size of a project before starting. If, for instance, a program starts out as a simple Perl script for parsing an input file and later ends with a request for a GUI to be added and additional functionality I'm better off starting over and rethinking the final design then just pasting on the necessary changes to meet the new requirements. Otherwise, the project, although still small and maintainable over a week or two is complete chaos when revisited in say a month or two.

Comments do matter, however; it does seem over commenting is just as much of a problem as no comments or under commenting. I have been handed projects from long gone developers that have had more comments than code. While it did give insight into what they were doing it became hard to find the code amongst all the comments, even with color coding turned on. It's an artistic poetry of having the right thing to say and saying it correctly. Which I am far from doing in this post.

The automatic checks on everything that you mention, exception handling and such, should be designed into the project from the start. Grafting it on after the fact is a nightmare and I have pity for anyone that is asked to do this and especially with code that is not theirs.

A good approach to design, I believe, trumps everything though. If you can hash out truly usable requiremets and implement a good personal software process and stick to it documenting as you go the end product always seems to turn out many notches above par even for small projects. However, none of this ever seems to occur where I work. Half baked requirements and a lack of time to properly design and implement seem to be the norm.

Re:Coding style (4, Insightful)

AuMatar (183847) | more than 9 years ago | (#11882523)

[quote]Most critical is managing complexity. Large, complex functions are bad - they have more bugs, they are harder to maintain, harder to bug fix (a change has more likelyhood of breaking something else). If a function has grown beyond a hundred lines of (real) code, it is almost certainly too large. If it has more than 4 levels of nesting, it is too large.[/quote]

The problem with hard fast rules like that is they're frequently not right. Take a state machine for example. A simple one with 6 or 7 states will go over 100 lines, and will go over 4 nestings. Heck, you'll take one up with the loop and one with the switch alone. You can break it into functions and hide some of the nesting in functions, but when doing that you frequently end up with functions that don't make a lot of sense by themselves.

A better rule than size IMHO is the one logical operation rule. A function should do one logical operation (read a file, write a file, run a state machine, calculate something, etc). They should contain all the logic needed to do that operation plus any debug and error handling that makes sense at that level of code. They should be broken up into subfunctions ONLY if those subfunctions themselves follow the logical operation rule, and only if that logical operation makes sense outside of the context of the higher function.

Take the state machine example. If it needs to wait on a semaphore before each iteration, the wait should be its own function- waiting on a semaphore is a logical operation. The logic for each state should NOT be separate functions, they are part of the state machine and make no sense without the whole of the machine for context. Breaking them out results in harder to read code, even if you do lose the nesting. But if in case RUNNING_MOTOR you issue a stop command to the motor that probably makes sense to be its own function- how you actually stop the motor isn't part of the core logic of the machine.

I guess my point is- lines of code isn't the enemy, some things are complex and need many lines to do. Nesting isn't the enemy, some things require many loops/ifs. The enemy is a lack of clear separation of functionality and lack of clear abstraction between parts. If you have separation and abstraction, it tends to hit the optimal readability. If you don't, it will fail either because you broke it up too much (too little context) or too little (too much context).

QA (2, Informative)

Anonymous Coward | more than 9 years ago | (#11882257)

I'm doing QA on all work delivered by contractors that is on our standing offer list (yes, I work for the government... and yes, there are a few good people here).

First thing you notice is that they hardly ever read the statement of work before they start coding. The whole application becomes a hack.

Second thing is the structure of the code. Indentation? What a heck is that? Some try doing indentation by just using the tab key. That looks great for someone who has the tab size set to six... after 13 levels (extreme, but I've seen it), you can't see the freaking code. My advice to someone who's in charge for a codebase... Standardize indentation, as well as the tab setting.

Third thing you notice is that they've changed the structure of the database that you provided to them. Oh, great!.. There goes the lean structure, just so that the coder could perform a quick hack by duplicating the data throughout all the tables.

If you want code to be maintainable, do QA, and do it good!

Re:QA (0)

Anonymous Coward | more than 9 years ago | (#11882353)

i've found CMMI, or at least some mature methodology is absolutely required for huge projects to not become more then hacks.

heck, it's even good for medium sized projects.

small projects need not apply (though some of the ideas are definitely applicable).

Re:Indentation (1)

Feneric (765069) | more than 9 years ago | (#11882453)

One of the good things about the Python language is that it forces indentation. And it doesn't have insignificant indentation that can lead to bugs. Two, two of the good things about Python are...

Seriously though I've seen enough cases of buggy things like:

if (condition)
statement one;
statement two;

that were meant to be:

if (condition) {
statment one;
statement two;
}

to appreciate a language that doesn't encourage one to meaninglessly indent code but instead actually uses the indentation to determine blocks.

(Unfortunately /.'s ecode tag doesn't seem to preserve leading spaces, so you can't actually see the indents -- I'm guessing though that most readers will know where they're supposed to be.)

Re:QA (1, Insightful)

Anonymous Coward | more than 9 years ago | (#11882563)

If you encounter more than about 4 levels of indentation then the width of a tab is the least of your worries.

language bias detected (3, Insightful)

anomalous cohort (704239) | more than 9 years ago | (#11882271)

In Chapter 2, a number of concepts basic to any programming language are covered, including the basic flow-control units common to many languages. The book focuses on C, with additional coverage given using C++, Java, and a few other things thrown in for good measure. As such, these chapters -- in fact the whole book -- focuses on concepts common to these languages but absent in some other languages, like Scheme or LISP.

Hmmm. What concepts, particularly what basic flow control concepts, are present in C, C++, or Java yet absent in Scheme or Lisp?

Re:language bias detected (4, Funny)

KenSeymour (81018) | more than 9 years ago | (#11882355)

I would say the concept of getting paid for programming.

Re:language bias detected (4, Insightful)

Jerf (17166) | more than 9 years ago | (#11882427)

The author is probably referring to the way Scheme and LISP are "missing" static type checking, in much the same way I am "missing" a hole in the side of my head.

The claim that something is missing would be more compelling if they weren't "missing" it on purpose, and the trend wasn't swinging in the dynamically-typed (or, as I think of it, "value typed" as opposed to "variable typed"; whatever you do it's wrong to call it "weakly typed") language's favor anyhow.

(Variable-based-typing's only hope is that the type-inferencing languages penetrate into the mainstream before the recoginition that variable-based-typing isn't free does, that being the fundamental misconception keeping it afloat. (Once you ack. the obvious point that it is not free, and is in fact quite expensive, both in actual effort and in massively underestimated opportunity costs, you are suddenly able to consider it in terms of costs and benefits, and the cost/benefit analysis generally does not work out in its favor when done dispassionately, though there are exceptions.))

Re:language bias detected (1)

rubycodez (864176) | more than 9 years ago | (#11882439)

all the stinky ones, like goto and external iterators 8D

Re:language bias detected (1)

brpr (826904) | more than 9 years ago | (#11882480)

Common Lisp has goto. Scheme has call/cc which can be used to implement gotos.

Re:language bias detected (2, Insightful)

d1v1d3byz3r0 (758848) | more than 9 years ago | (#11882449)

If they don't exist, you can always build them in. That's the beauty of Lisp.

Off the top of my head, I can't think of any major flow control mechanisms missing from native Lisp. If they exist, I'm pretty sure there was a good reason that they don't exist in Lisp.

Amen (2, Interesting)

MHobbit (830388) | more than 9 years ago | (#11882288)

Amen.

I've been coding for a couple of years now, and always have been using comments. Mind you, I only started using a lot of them when I started with PHP code and other open-source, interpreted languages.

Right now, I'm still a better C coder than PHP, and you can tell by what approach I take to solve various things.

"Code is its own documentation, right?" (5, Funny)

guitaristx (791223) | more than 9 years ago | (#11882290)

From someone who's had a hand in dealing with function pointers named StupidSuckingGlobalCallbackFunction, trust me, the subject of this post is very, very, very wrong.

Learning from decades-old code (4, Informative)

shoppa (464619) | more than 9 years ago | (#11882292)

I've had many opportunities to work with code that has evolved over several decades. There are two common patterns:
  1. Project was originally a quick hack. It lives well past its prime, gets modded extensively to handle changes going on in the real world (new devices, competition, etc.). Abstractions are added where necessary. Some hacky ugliness lives at fringes, but after umpteen releases and way too much backwards compatibility customers are still buying it.
  2. Project was a grandiose dream by an analyst. Before any functionality exists, everything is abstracted to the max. 10-inch thick binders full of API's are published before the product actually does anything. The abstractions usually turn out to be wrong, and after many years (and little functionality) either the abstractions get twisted around at great expense to reach functionality, or the project dies in heaving paroxysms.
. Reading the experienced coder's comments is always good. They know the history and want to pass on the lessons learned to whoever will look.

Re:Learning from decades-old code (1)

14erCleaner (745600) | more than 9 years ago | (#11882407)

Reading the experienced coder's comments is always good. They know the history and want to pass on the lessons learned to whoever will look.

I have to disagree with this. Just because a programmer is experienced, that doesn't mean he can write good code, or comments. I've worked with (and had to clean up after) many experienced programmers who were incapable of writing clear code, or clear comments explaining what their code was trying to do.

Writing takes talent, not just mileage.

Re:Learning from decades-old code (1)

Sweetshark (696449) | more than 9 years ago | (#11882581)

Actually you need a old type 1 Project to do the analysis for a good rewritten type 2 project dropping most unneeded backwards compability.

(Example: type 1 sendmail, type 2 postfix)

Code format (0)

Anonymous Coward | more than 9 years ago | (#11882298)

All I gotta say is that if you use {
this {
style {
of indention
}
}
}

You are a newbie.

Use standard
{
ANSI formatting
{
you kiddies
}
}

Re:Code format (3, Insightful)

Cthefuture (665326) | more than 9 years ago | (#11882386)

I have to say that I agree with you to a certain degree.

I'll go one more step though. It's about white space. You can almost always recognize a good programmer by how clean the code looks because of proper use of white space. If the code is all crammed together and cluttered looking then you know that programmer sucks. White space does not make your code slower guys!

Note that I said this is a way to recognize a good programmers. Often experience plays a role but I see a ton of fairly experienced programmers that write ass crappy code.

I see a lot of people saying comments are also a sign but I have to disagree. Well written code is easy to read and figure out. I would much rather have nicely written code than comments. (Note that it is my job to fix other people's code so I have a lot of experience with this)

Re:Code format (1)

sqlrob (173498) | more than 9 years ago | (#11882488)

Right Braces = Good in inline in headers
Left Braces = seperate files

Re:Code format (0)

Anonymous Coward | more than 9 years ago | (#11882576)

There is a rat in separate.

comments (5, Insightful)

defile (1059) | more than 9 years ago | (#11882317)

If the expression itself requires a comment, then it is not being expressed clearly enough. It should be rewritten.

If the expression is clear, but does not make sense in the context, appears suboptimal, or otherwise thwarts the reader's expectations, THEN I'll comment.

Real world project comments...

  • We're using this byte[] array wrapper because Java won't hash identical byte arrays to the same value.
  • This is in fact a bubble sort. I'd call qsort(), but it's nowhere to be found and I'm not going to implement it myself just for this. Additionally, it doesn't matter since it sorts at most 100 records, and it's called very rarely.
  • Why yes, it IS a giant waste of space to represent an 8-bit value in a 16-bit quantity. But someone thought it was a good idea to leave out unsigned.
  • Unlike everywhere else, here we're waiting for key-release instead of key-press because the operating environment has a race condition and posts them out of order! Go Sun!

editor? (0)

Anonymous Coward | more than 9 years ago | (#11882335)

What editor they use,

You can judge how good a programmer is by what editor they use? Well, I use that method to rate authors before even reading a word of their work. And, when I'm a judge at the olympics, I just see who has the best bike and give them the best time.

The art of code (2, Insightful)

achacha (139424) | more than 9 years ago | (#11882336)

There is a lot of truth to coding style that is not necessarily related to open source. Seasoned programmers work very hard to keep naming, patterns and even formatting consistent. It makes it easier to read.

The open source angle is that the code will be viewed by many people and thus there is a greater detail to presentation, it's a form of ego stroking and seems to work quite well.

I do code reviews all the time and I can tell a novice developer from someone who has done it for a while, it's a hard thing to explain, it's like a difference between good and bad art. And just like with art, you can have decent artists and you can have great artists with very little in-between. Go figure :)

Re:The art of code (0)

Anonymous Coward | more than 9 years ago | (#11882550)

it's a hard thing to explain, it's like a difference between good and bad art.

so Cmdr. Taco is basically Jackson Pollack?

Bad docs better than none (2, Insightful)

Acius (828840) | more than 9 years ago | (#11882363)

Having worked on some terribly buggy code with buggy docs, I'm going to suggest that even bad docs are better than none. Sure, you get burned once or twice, but you quickly learn not to trust the docs as canon. And while the docs often don't tell you what the code does, it tells you what the developer WANTED it to do, which is golden information when you're trying to debug.

Anyone have a "free as in beer" copy (0)

Anonymous Coward | more than 9 years ago | (#11882504)

please post it here, i mean this is slashdot right, the face of the free movement

Indeed! (2, Insightful)

kraksmokr (216277) | more than 9 years ago | (#11882554)

After spending many years as a programmer, and writing thousands of lines of code, I have learned so much about coding that these days I find myself not writing code at all, or very little code.

As a young freshly trained programmer, you are walking around with a hammer, and a lot of things look like nails.

You think you are a badass because of the power and precision with which you hit the nails.

Then one day and you see you are building a house. And there are a lot of other people whose work is instrumental to getting the house built.

So after a while you start telling other people how to hit their nails, and before you know it, you are building entire tracts of homes.

my technique (2, Informative)

SQLz (564901) | more than 9 years ago | (#11882565)

I'm a scripter (php, python, perl, java etc) and I work with other scripters. I notice a big difference in code depending on the age of the programmer and what programming language they started with.

My technique is pretty much opposite from anyone elses where I worl, although, I don't know of this is a good thing or not.

I start off with making tons of functions. I go crazy with functions and usually put them into related objects/packages with static methods just for organization purposes....so I quickly know where to look when I want to edit the behavior. I always maintain the PerlDOC/PHPDoc/JavaDOC comments even when I first start out because my IDE reads and pops up nice little hints when I forget arguments but other than that I don't comment too much unless I'm doing something dicey. Once I've coded enough, I start to see the places where I can refactor and abstract a lot of the functions away and weed out any inconsistancies really quick.

Others tend to make one gigantic script with little or any functions and tons of global structures and arrays then refactor it to a more sane style later on.

Their moto is "first get it working, then get it working right". My reply is "that doesn't mean you throw good programming practice out the window.";

Load More Comments
Slashdot Account

Need an Account?

Forgot your password?

Don't worry, we never post anything without your permission.

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>
Create a Slashdot Account

Loading...