Code Reading: The Open Source Perspective
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.
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.
... you're saying that there's more to it than just getting it done?
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.
You can tell a great deal about the maturity of a programmer by the quantity, and quality, of comments.
Unfortunately, some experienced programmers write like ee cummings, and others like avant-guard poets.
Have you read my blog lately?
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
"A door is what a dog is perpetually on the wrong side of" - Ogden Nash
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?
Speaking of which, I was recently browsing sourceforge, and happened to notice this project which MUST be a good one since its home page has an error screen:
/home/groups/c/cp/cphp/htdocs/funciones.php on line 4
:)
Fatal error: Cannot redeclare fecha2mysql() in
Not to mention they misspelled 'functions'!
This project can be found here, and there homepage here.
Oh yeah, if you happen to be reading this, agustindondo, no offense intended
<overrated>Insert Sig Here</overrated>
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
The smart man learns from his mistakes ...
... but the wise man learns from other peoples mistakes.
:-P.
I guess that I am just kind of average
Cheers,
Adolfo
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.
I am waiting for the intelliSense to suggest the word!
Great ideas often receive violent opposition from mediocre minds. - Albert Einstein
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
Anything I post is strictly my own thoughts and doesn't necessarily have anything to do with the opinions of IBM.
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...
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!
Hmmm. What concepts, particularly what basic flow control concepts, are present in C, C++, or Java yet absent in Scheme or Lisp?
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.
Debugging? Klingons do not debug. Bugs are good for building character in the user.
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.
I pity the foo that isn't metasyntactic
- 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.
- 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.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...
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
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.
I pity the foo that isn't metasyntactic
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.
Acius the unfamous
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)
The ratio of people to cake is too big
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!!!
There are 10 kinds of people in the world, those who understand binary and those who don't...what about the other 8?
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.
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)that were meant to be:
if (condition) {}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.)
Right Braces = Good in inline in headers
Left Braces = seperate files
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.
Those who can make you believe absurdities can make you commit atrocities. - Voltaire
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.
Don't get me started about projects architechted by interns and implemented by highschool dropouts!
the preceding comment is my own and in no way reflects the opinion of the Joint Chiefs of Staff
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.";
Wait... let me write that down :-).
Get an account AC and harvest some karma.
Cheers,
Adolfo
YES. You can tell because a good programmer will use the best tool for each thing. None of that stupid editor religiosity ("Visual Studio is better!" "No, Emacs!" "Vim is the way to go!"). That is plainly stupid.
As a PHP/Perl/JavaScript/HTML developer, here are some of the things I think I do well:
Where I fail at coding:
My Greasemonkey scripts for Digg &
One of my favorite aspects of Objective-C is the way methods are self-documenting. "[Object doThis:something toThis:something]" is easy to figure out.
I don't understand
// Begin Comment Header
// Comment Author:
// John Smith
// Programmer Analyst
// john.smith@company.com
// Comment Version:
// 0.0.1
// Comment Date:
// 2005.03.08
// End Comment Header
// Begin Comment
// increment i by 1
i++;
If the code doesn't match the documentation, then you have found a bug! Either the documentation or the code is flawed: you need to revisit the actual requirements to determine which is the case. This may require revisiting the problem at it's source to determine the business, hardware, or safety requirements. When you find out the required behaviour, code it correctly, and then document it correctly!
If you blithely rely on either the code *OR* the documentation to be correct, you're being far too trusting...
The opposite argument also works- the one time I was forced to use python (maintenance work of a contractor who loved the language) I spent 3 days tracking down a problem. The problem was he didn't indent when he meant to, making something outside the if.
The there was the problem when our prettyizer fucked up the master by changing the spacing on check in. That was a nightmare. And of course ithe fact I like to use 2 spaces to indent and he used 4 caused problems.
WHich is why indentation is a BAD way of doing nesting. It ought to be done in such a way that meaningless differences in writing style like indentation and spacing don't matter. Perl gets it right- ignore spacing and require {} pairs on all nesting statements.
I still have more fans than freaks. WTF is wrong with you people?
This style
{
is better by far
{
because the braces 'belong' to
the following block of code
}
not the
{
preceeding guard statement
}
}
Sincerely,
An OFP (Old Fart Progammer)
Generally, bash is superior to python in those environments where python is not installed.
The title says it all.
All I gotta say is that if you use {
this {
style {
of indention
}
}
}
You are a newbie.
No way! I have been coding for 30 years...
It makes more sense to code
if (test) {
statement1
} else {
statement2
}
because the eye can immediately see from the 'if' and 'else' statements alone that a block of conditional code follows. Having the braces on the same line also marks out the lines as special: flow control code. I find that
if (test)
{
statement1
}
else
{
statement2
}
simply adds pointless extra lines to code, with no gain in readability.
I've tried to work on projects where we developed new software as much as possible. However, taken all together I think I've probably spent many months of aggregate time reading other peoples code, modifying it, adding new features and fixing bugs. I hate doing this work, not only because of poorly designed software but because most software I've worked on is almost entirely undocumented (e.g., no comments and no external documentation).
Some posters have mentioned comments and documentation in this thread. But in my opinion, it has not been discussed in strong enough terms. For a long rant on this topic, see my essay Software and Documentation. I'll summarize some of the points I try to make in this essay here.
There were only a few people in this thread who wrote that they think that software source code is self documenting. This is a good sign. In the past this was a widely held view. Perhaps it is becoming less popular. Perhaps pigs are becoming airborne.
To those of you who wrote that your code is self documenting: you are simply lazy and unprofessional.
Sure I can understand what well written code does. But I cannot understand why it does what it does. I can show you three hundred lines of wavelet signal processing code. You can immediately understand what the code is doing. But you will have no clue what-so-ever about why it does what it does unless you understand the thinking behind the code. The same is true of any complex software.
Another problem is that even though I might understand what components do and perhaps even why they are doing what they do, getting an overall understanding of the architecture of a large application can be difficult and time consuming.
By not writing comments in your code and, for large applications, providing external documentation on the architecture, you are saving your time and effort, but forcing others to spend effort that you could have saved them.
Even if you have no consideration for anyone else who must maintain the application after you write it, comments will help you find bugs in your own code. Again and again I have found that when I explain my code in a comment I am forced to look over it again. In doing this I have found that the code does not do what I intended or that I left something out.
When it comes to documentation there is rarely enough. Even if you make an effort to document your code, when you are in the middle of it you will not document things that you find obvious. When you return later, these obvious issues will have been forgotten and are not obscure.
Documentation must be maintained along with the code. And it should be extended where it is incomplete or unclear. English (or what ever your language is): it's another kind of software.
Developers seem to fall into two camps: those who believe documentation is important and who do it and those who do not. I've managed software groups where I mentioned documentation in people's performace reviews and it still did not good. So far I have not been able to get someone who does not document to do it.
I have thought that perhaps one solution would be to hold code reviews where one of the major features that was looked at was understandability in the code. But I have not experimented enough to know if this will actually get people to document their software.
Literate programming not only involves writing well designed and well informed algorithms. It also includes writing documentation that explains these algorithms.
But many "newbies" such as Kernighan, Ritchie, and Torvalds all highly recommend the One True Brace (OTB) style. It's the one used in the K&R's C book, among other things. In other words, some of the people MOST exerienced with C use this style.
There are serious advantages to the OTB style. In particular, it eliminates useless white space so that you can actually see more vertical text simultaneously -- even with big screens that's helpful.
If you want to use a different style, go ahead! If you're the lead, I'll gladly use your style. But in programs I lead, I'll continue to use OTB and expect others to follow suit. Oh, and I've been using C since 1985, so !newbie.
- David A. Wheeler (see my Secure Programming HOWTO)
Linus Torvalds (Linux kernel)
W. Richard Stevens (Advanced Programming in the UNIX Environment and UNIX Network Programming)
Brian W. Kernighan (C Programming Language co-author)
Dennis Ritchie (C Programming Language co-author)
Gamma, Helm, Johnson, and Vlissides (Design Patterns)
Hmmm. You are a newbie. Kernighan and Ritchie wrote the book on C, literally, and the ISO C standard still uses their style. The opening brace is only by itself when starting a function body. In all other cases, it shares the line.
From Structure and Interpretation of Computer Programs by Abelson and Sussman:
"Programs should be written for people to read, and only incidentally for machines to execute."
A long time ago (I know I'm dating myself here!) Dr. Dobbs had a book called:
:-/
:-)
Dobbs (extracts from Dr. Dobbs Journal)
Dr. Dobb's Toolbox of C
Prentice-Hall 1986
This book laid out the various methods which they used in the creation of Small C. I took those lessons to heart and programed by them. Although a lot of other methods have been forced down my throat by would-be managers or people who knew something about coding - these techniques have been, IMHO, the most help I have ever had when it comes to coding software.
The book explained the WHY of "why should you indent", and WHY you should use meaningful names for variables. In fact, it explained a lot of the WHYs and WHEREFOREs of programming.
If you can get your hands on a copy of this book - you should do so. Mine died a sudden death when, around Christmas time, the ceiling in my computer room came down. I was living in an apartment at the time and a water leak caused the ceiling to collapse. Know what gypsum becomes with some water? GLUE! So several of my really good books died that day from being glued together. Unfortunately, Dr. Dobb's book was one of them.
Luckily, the ceiling collapsed where the books were stacked and not where the computers were stacked. That would have been an even worse nightmare.
To bring this back on topic: I haven't read this new book, but from the overview - it sounds a lot like Dr. Dobb's book. So I may be off to buy it soon just to check it out.
Someone put a black hole in my pocket and now I'm broke.
After visiting the local Sr. Frogs last night I think of the following words and phrases as useful to the average United Statian: Cultura means "culture", gringo is often reserved for United Statians -or whatever they should call themselves-, and the phrase no conocen de otras means "are ignorant of other". There's also gringuitas ricas, which translate roughly to something like "nice, young, united-statian college girls".
HAD
Once I was asked to code something for a project that I knew I was about to be forcibly removed from.
I named functions and variables the most obscure things I possibly could, left as little whitespace as possible, and used x ? y : z, instead of if(x) { y; } else { z; }.
Those bastards learned nothing from me.
WordStar kicks ass, and joe is like WordStar.
Therefore, joe kicks ass. Alan Cox uses joe.
Unlike vi, joe is easy to operate over all sorts
of defective terminal emulators. For example, vi
users are screwed w/o the escape key. I've seen
that twice, on a real DECstation (OK, you could
use the F11 key to get an escape...) and on a
telnet program for the Mac.
No problem for joe!
Don't get me started on emacs...
This is why there are python "guidelines" for how you should indent. (IMO it should be standard and forced to avoid these problems)
;)
Hopefully more languages will get this strict and we'll actually be able to read other people's code in general in the future.
People's petty little preferences and habits aside, it is a good thing, and you know it.
ok, maybe not a newb, but your code still looks like crap.
.. THEN, so you should not split up if(..){
<jar-jar>How Woood!</jar-jar>
I have explained clearly and logically why the code I showed is easier to read....
if(condition)
{
in Java/C++/C#
Is as dumb as
IF condition
THEN
in more verbose languages
You don't split up IF
So you need guidelines to make a bad design decision work. This is what is generally called a "hack". The real solution is to not give semantic meaning to whitespace in the first place.
I still have more fans than freaks. WTF is wrong with you people?
Any other newbies remember this from fortran or am I just high again ?
:). Sheesh, I even remember Algol!
I remember
Ah, like Vetinari, The Patrician ... he enjoyed reading music. He didn't want to play it, or listen to all that noise, merely to read it.
Do not mock my vision of impractical footwear
I have used this style extensively in the past and I agree.
I don't tend to use that format though because it's so rare that people crap their pants when they see it and start complaining. It takes a little getting used to but once you get used to it, it works a lot better.
These days I use whatever style the project is written in but I much prefer your style or ANSI style. I usually just use ANSI style so that other programmers will at least accept it.
The ratio of people to cake is too big
Both consistency and good comments are good traits. I find understandable function and variable names are essential as well.
I believe that language familiarity has little to nothing to do with being a good programmer. A more familiar programmer can program faster but programming principles remain the same across all languages.
Smaller, simpler code is inherently less likely to contain bugs, runs faster, and is easier to troubleshoot.
If programmer A develops 1000 lines of code per day and programmer B develops 10 lines of code per day and both programs do the same thing I will pick programmer B every time (normal lines of code, not contest entries with runon lines and things)
Coding Blog
If you write Prolog or LISP, nothing can help you.
Out of curiosity, when you sit down to a fresh, steaming pile of someone else's code, do you start by running the whole thing through a pretty printer? I'm half way through a class on compilers, and it looks fairly straightforward to write one. I've always had a hunch that it would be a good way to enforce certain coding standards for a project.
So what's your experience been?
You want the truthiness? You can't handle the truthiness!
Who cares - as long as nobody understands my code, my job is safe :)
--Sir_-_Jeff--
Not often, but sometimes. I try to keep the same style if possible. Engineers seem especially bad about writing cryptic, compressed, broken code.
Artistic Style (astyle) is what I use to reformat code.
The ratio of people to cake is too big
Excepting HTML maybe, none of the Slashdot posting
options make any sense. They don't do the obvious,
at least not fully, and the oddities are not
documented.
Try filing a bug in the Slashcode Bugzilla.
When I programm ERP Modules (in Python) I start with a large comment on what the module is supposed to do. I actually started doing this quite from the beginning. I write a litte summary of what the module does and comment heavily throughout the source. I even have debugging sessions were I only work on comments - often detailing them further.
I also do a lot of other programming (ActionScript rich media and stuff). I don't do opening or other comments there that much.
Why that?
If a multimedia app doesn't work I get an e-mail or a call asking to check into it within the next 24 hrs. The customer is anoyed or says that this comes bad with the end-user. We talk a little, I et to work and fix it within the next 10 hrs.
If a ERP module doesn't do what it's supposed to, I get a call on my mobile, with the CEO at the other end telling me that he's losing 200 Euro an hour because order processing has gone haywire.
This is a good point to end all discussion wether commenting is good or bad. When you are debugging a piece of code that keeps 3 people breathing you shure as well want it to be well commented.
The Lockheed Software Group, the people who write code for the space shuttle and other things, take this to the all-out extreme. They write EVERYTHING in a sort of human readable meta code, meta-comment THAT and then tranfer that to real code. They've had 3 bugs in 25 years - so I've heard. One of them being a counter problem that once would have nearly locked down a com-dish on an orbiter and prevented it from following it's target on earth after having rotated a certain amount. Figure: A millisecond of timing error in their code has the orbiter off course by 3 miles. I hear their comment line/code line ratio is about 7 to 1.
So much for "overcommenting is unprofessional".
We suffer more in our imagination than in reality. - Seneca
CVS usage should be at the beginning of the book. CVS has saved hours of work for me. Why isn't it part of standard programming education?
I have to quote the wordpress moto here
"Code is poetry"
It's what I live by now.
Wish I had mod points to mod you up.
As a rule, I avoid modding up Anon Cowards, but in this case, I'll make an exception.
To think of code as literature is actually a non-obvious and striking idea.
The essence of literature is communication. I've been writing C and C++ for years, constantly fine-tuning and refining code and documentation, line by line, paragraph by paragraph. And how apropos to realize that the point is to express the thought so clearly and concisely that any reader (including yourself three weeks from now) will grasp it as close to immediately as possible.
That means you have to think clearly in order to code clearly. This matters more than almost anything else.
Too much documentation is just as bad as too little, since it obscures the intent of the code. How much is just enough? It takes years of thoughtful practice to know that.
Everyone is posting their favorite rules about coding standards. Most young programmers apply standards as rigid as they are incomplete. I have only two rules:
1) Call everything by its right name. Functions are verbs, variables are nouns. The name you give a object should express what it is or does, no more and no less, and be readable in English (or whatever your spoken language is). If you add something to a function that doesn't fit the function's name, it either belongs in a different function or else you misnamed the function in the first place. This takes constant review of your code, from a literary point of view.
2) Rules are made to be broken. All great writers unhesitatingly break the rules in order to communicate more clearly.
Languages are for communicating, and computer languages are no different. Keep that in mind at all times, and you'll become a wizard.
Responsible laziness is key here. Be responsible enough to comment unclear code; but be lazy enough to prefer rewriting the code for clarity to banging out a comment.
My best C++ code has no comments. All the names are pronouncable and meaningful. The code is just as readable as a comment would be, but it can't get out of date with the code like a comment does.
I make an exception for class-level comments giving the code context in the program; those are good.
I cannot agree more. In fact, I have become somewhat of a code-nazi when it comes to this. Well spaced code allows it to be easier to read, like words and paragraphs.
I know this is off topic, but...
Sometimes what is construed as the 'best' tool for the particular task at hand for one, might not be for another.
I'm particular about vim. Now, this does not mean I'm on a 'religiosity' rant, if you want to use emacs, or any other particular IDE, that's fine with me. It's just that I have used various IDEs that are more particular to the language at hand (namely, eclipse and netbeans), and have found that I'm more productive using vim.
Funny, the argument works better the other way:
No way! I have been coding for 30 years...
It makes more sense to code
if (test)
{
statement1
}
else
{
statement2
}
because the eye can immediately see from the BRACES alone that a block of conditional code follows. Having the braces vertically aligned also marks the contained lines as special: flow control code. I find that
if (test) {
statement1
} else {
statement2
}
renders most control-flow logic completely unreadable since there's no white space to set off conditionals from other forms of code. White-space is cheap, if you're still using a 25-line green-phosphor terminal to edit code I highly suggest you look into retirement; let those crazy youngsters with 1600x1200 color bitmapped displays write the code (with all due respect).
...to which I can only ask, "Where the hell have you all been for my entire career?!?!"
I only meet the morons that can barely code, much less comment or design.
"Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
The Lockheed Software Group, the people who write code for the space shuttle and other things, take this to the all-out extreme. They write EVERYTHING in a sort of human readable meta code, meta-comment THAT and then tranfer that to real code.
Not quite. What differs from most other shops is that they rigorously do design reviews, code reviews, unit testing, and integration testing. A product stays in a maintaince phase for years before ever being shipped.
There's not that much more commenting in the code than in any other large software product.
While I find the full Hungarian notation excessive, a subset of it specifying only the location of the variable can be very valuable. When you are looking at a variable, one of the most common things you want to know about it is where it is declared. With hungarian m_, g_, and s_ prefixes it is immediately clear where to look for the declaration if you need it.
> dealing with function pointers named StupidSuckingGlobalCallbackFunction
When you have functions named like that, don't write documentation for them. Rename them. It takes a lot less effort to write code so its meaning is obvious then to write documentation explaining why you didn't do that.
i agree. also, if i have a sql statement:
$some_q = " SELECT *
FROM x.table
JOIN y.table USING(a)
WHERE b = 0";
so that the statements (most much larger than this) are more readable. tabs only please, set to 4 spaces.
Comments are poor substitutes for readable code. Not bashing comments, but frankly, 95% of comments are useless drivel.
> (I know I'm dating myself here!)
Don't worry, we all do.
That's because you look at the braces. I look at the indentation to provide visual breaks. A brace on its own line is confusing when you are used to the cuddled kind because it creates an extra block. My brain automatically sees the if as a one-liner followed by an unrelated block. In other words, I would interpret it thus:
For those who don't feel like reading 1 through 11.
www.ralford.net
You are a newbie.
I would say just the opposite. The people I know that are just being taught how to program use the ansi style format. The veterans who have been coding for awhile use the other non-standard format (for readability..I prefer the non-Ansi format of commenting).
Hence, simple algorithms will likely have no comments in the implementation.
More of the time, comments that "supplement" the code usually add to the confusion for most advance developers.
or simple counters I find that using i or j or similar works quite well. After all, everybody understands a for loop with an i index -- calling it array_index_counter or some-such is (IMHO) pointless.
No, array_index_counter is worse than pointless, using i or j is recognizable to any good programmer, no though required. Using array_index_counter implies that there is something other than a loop index going on with the variable and causes all good programmers to pause for a moment to figure out what that is. (Only to be annoyed when they realize it is just a loop index)
There is one other program with descriptive loop indexes: they take up too much space. The example you gave it 19 letters, and in a typical C for statement will be repeated three times. That works out to 57 letters. Add in a few for the other required parts, and indentation, and you are longer than the typical terminal line, and all hope of easy readability is lost. (Unless you expand the window, but that assumes you do all your editing in a graphical environment, which isn't always true)
You must have one bitch of a time hearing. ;)
News for Geeks in Austin, TX
I've been programming since 1985 and I still learned a lot from this book.
I've recommended it to many people and I just get blank stares like, "why would anyone want a book on code reading?" I have to put it in front of their face for them to understand.
Within a logical section of the code (a 'subsystem', for example) I do expect consistency, and I will adhere to the style found therein. But if given a choice (I'm creating the subsytem), I'll use the above. It's just vastly cleaner to the eye.
Generally, bash is superior to python in those environments where python is not installed.
If this number is correct, most likely the "7" refers to all the documentation behind the code. Requirements, design, review comments, testing, actual comments etc. So i wouldn't be at all surprised to hear a 7:1 documentation to code ratio. But a 7:1 comments ratio just for comments in the actual code seems highly unlikely; it would make the code almost unreadable. Imagine trying to read a story when between every sentence there are a few pages of pictures.
Especially when you get into nested..Bringing the brace down, but not adding the extra line conserves the space lost with the latter method and keeps the connection between the test and the block, but at the same time makes visual "chunking" of the code blocks that much easier by having the open and closing braces in the same column.
That Jesus Christ guy is getting some terrible lag... it took him 3 days to respawn! -NJ CoolBreeze
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.
Eat some pussy before going to bed? You sound pretty whipped to me. I either get my dick sucked by my girl or stick my dick in a pussy and blow a giant load in her mouth or pussy (and sometimes in her ass). I never ever have to eat her pussy. Eating pussy is for lesbians.
I think the idea that geeks can't get laid is a huge misconception. Eventually some woman gives us a chance, and after years of masturbating we have such good sexual control and technique that we're able to make her cum like she's never cum before. That's what happened to me anyways. Having said that, though, having someone to fuck is really not that big of a deal, I don't know why people act like it is and put down people who can't get laid. Yes, sex can be really fucking good, but it doesn't improve you as a person to be getting it. If you were a stupid fuck before getting laid, you're a stupid fuck after getting laid.
And yes, I am one of those open source hippies. But I get paid for leveraging open source technologies. And I get laid. Boo-yah!
Zoot!
Because your style of brackets merges the bracketed code and the conditional into one blob, you also can't quickly comment out the conditional (leaving the code). For example:..vs having to mess with the end bracket as well:Anyway, my 2 cents.
Have you ever been in a code review that was a comment review? Where the reviewers, unwilling or unable to find problems in the code, nitpicked about how the comments looked like? Too many managers and second tier programmers spend their time worrying about the details of the comments and coding style because that is all they understand.
What good are great comments if the code doesn't work? Sure, comments matter, but all of the comments in the world aren't going to make buggy software run better. It will just make the next programmer understand how screwed up the original programmer was.
Sometimes, like in my case, it is not usefull to coment the code I write. I try to go beyond that and even make it as unreadable as posible. Writting unreadable-unmantainable code make your self unfireable. What happen if no body else but you is able to keep on working the modules you have written. I just keep clean the interfaces. Their inside is mine and just mine and nobody else should be ever able to understand a word. It keep my workplace safe.
That's because you look at the braces. I look at the indentation to provide visual breaks.
That's not smart. Indentation can (and where I work, quite often does) get messed up. But the braces never lie. (Similar to comments vs. code.)
Also, if your brain tends to interpret that bracing style that way, how often do you come across a stand-alone, unconditional, embedded pair of braces within say a function body?
Attention zealots and haters: 00100 00100
I've been programming in PHP for about 2 years, and programming in general for 16 years. I've always commented my code since I started programming BASIC on my Apple IIe. I would usually put stuff mostly for my own reference. When I release my source code, I usually go in and add more comments.
http://phpdoc.org/
PHPDoc (inspired by JavaDoc) helps me write better comments by formatting my comments using tags. It makes a reference manual for my code in multiple formats. Now instead of comments, I make DocBlocks. Page level DocBlocks describe the general purpose of the file. You can group files together in packages. It helps to see how it all looks from the user's perspective, no matter what language you are using.
SproutWorks Software Design
Exactly. I've had to wrangle with multi-page behemoths at my first job, and it's a lot easier to find the brace missing his buddy by using the IDE's "jump to matching brace" hotkey while watching the column # display in the status bar. With the style of matching braces not in the same column, you can't use this technique to help you.
Attention zealots and haters: 00100 00100
There is a lot of emphasis on comments here, and while I agree that the commenting style and opportunity seized by a programmer gives away a lot about the insight of programming, I just felt it necessary to add that commenting is not the holy grail either, and certainly not the final and decissive way to judge a programmer. Comments have the annoying property to become outdated. Especially when code ownership is blurry, comments in code tend to become obsolete or unapplicable. Despite all good intentions of the programmer.
It is better to 'read the code' instead. And if you 'can`t read the code', it means that the code sucks! Plain and simple. Then it`s time to refactor, and make sure that you can read the code as if it tells you a story about what happens with data, and why. Real good programmers know how to abstract and describe this process using architectural elements and design patterns, and without the need for a lot of extra commenting.
There is no algorithm that is so complex that it can not be put in a more or less readable form in code. Use abstractions and propper long names for classes, variables and fucntions. Describe with code what you are doing, and use small comments in-between to explain the progression within the algorithm, but refrain from writing large texts and function header comment blocks or whatever. They will become incorrect and misleading, and they are a drag to keep updated.
The only reason where I could think of using extensive comment sections in your code is to feed document system code parsers like Doxygen or Doc++ etc.., but that is only usefull if you`re writing an API, and when you know that 90% of that API is stable and will not change much.
With great power comes great electricity bills.
arrrg.
you are a newb.
You've obviously not only been coding for 30 years.
But coding THE SAME WAY for 30 years.
Amazing! Your ability to determine the details of long software engineering career simply based on the position of brackets in code...
You write string processing/parsing code in straight C because "it'll make it fast", when C++/STL has had a standard string type for *years*, and to top it off you:
Use idioms like this:
while( *ptr++ != NULL ) count++;
I can't believe I am reading this arrogant and offensive rubbish.
OTB style pisses me off because it makes it hard to match up braces for nested control statements (when your fixing somebody else's crap).
There is something called INDENTATION.
You realise all this is irrelevant anyway, as almost all good IDEs will allow the formatting to be changed anyway you like?
if (condition)
function();
I tend to do
if (condition) {
function();
}
always, even for single lines, as this is consistent and I always read if () { as 'if..then'
I picked up code reading about a year ago and began to devour it, only to walk away dissapointed. This is a book I wish someone had handed me when i was fresh out of college, but anyone with a few years of experience of working on large codebases is probably going to find little of value in here. Being told what if statements mean can be a little patronising. The section of the book that compares and contrasts structures from different languages can be useful if you are making a transition to a new language. The text is well written , but I would advise anyone who is thinking of picking up a copy to browse it in a bookstore first to make sure there is some valuable material for them in there before parting with their cash.
"In Xanadu did Kubla Khan a stately pleasure dome decree"
If you cannot run it through indent to format the code to your standard if you absolutely cannot read the particular brace style then you are newbie.
If you mix brace styles in the one source file or break a standard on a project THEN you are newbie.
I will stick to K&R formatting, I find your style irritating as you find my style. I get doubly irritated when people pointlessly reformat my code to make a 1 line change. Ever tried to QA that code and figure out what the real change is.
Easier for you to read, not for others. Amazing that this is a personal preference!
No. Many share my view, including Linus himself.
I can't even post your proposed equivalent of
class F {
int X {
get {
if ( disposed )
throw new DisposedException();
else
return x;
}
}
}
I keep getting:
Your comment violated the "postercomment" compression filter. Try less whitespace and/or less repetition. Comment aborted.
While whitespace, when used properly, is good for readability, the "{}"'s on seperate lines reduces readability by eating screen realestate with empty lines.
SLOGEN [ http://ungdomshus.nu : Sebastian cover music]
I actually have this book and learned a bit from it, even though I've been coding from the age of 6, not in c obviously. It actually contained examples of a few of the mistakes I made and enough of the examples allowed me to pat myself on the back.
// cuz I'm a bit of a nut...
I never got as far as the chapter on tools, but I'd like to add a note here on what I do for code readability:
As I have my own style I like to and can easily read code in that style, this is neither the BSD or Linux style, so I fire up the old indent program an convert it to the format I use. (It took me hours to tweak until I had the right settings.) Then I can read it in the style I find useful.
When I realease code I run indent over it to convert it to the style most used by most of the people in the project, or as in some projects the style that was defined as the project style.
I most note that sometimes I find myself typing functions as:
int func(var1,var2,var3)
int var1;
int var2;
int var3;
{
}
which I then have to change for the release versions.
'I am become Shiva, destroyer of worlds'
Although I understand your point most best practices say:
Your code should say what you are doing
The comments should say why
Your post suggests that you've got the first part (having clear code with sensible variable and method names).
----- If communism is a system where the government owns business, what do you call a system where business owns govern
You can tell a good tool from a bad only if you saw the person handling it. Some are good on vi, some on joe, some on emacs. Whatever you use, you must feel comfortable about it, I think. If one editor is cool just because it features a column-editing mode, then if you can achieve the same with just a few keystrokes in the same time, then what is the difference?. Its personal taste, really, so we can now go on discussing the best personal taste...
Black holes were created when god tried to divide by zero
No, the real solution is to strictly enforce exactly what one indentation level of whitespace is.
Vasstly differing code styles between people writing in the same language is nothing but a nuisance, and productivity/cooperation killer.
> Indentation can (and where I work, quite often does) get messed up.
How can it possibly get messed up? Nearly every editor has autoindenting mode, so if you want to mess up indentation you really have to try hard. Then, if it gets messed up, you should fix it. It's just like the comments vs. code: comments don't make the code good, they just make bad code better.
> how often do you come across a stand-alone,
> unconditional, embedded pair of braces
Not often, but it is sometimes useful to create an explicit scope as a precursor to pulling out a function. Its rarity is what makes standalone braces so jarring to my eye. Thankfully, I have indent, which takes care of that problem very nicely.
It's a vicious cycle. JVM developers say "nobody uses bytes or shorts anyway so we're not going to put a lot of effort into object layout optimizations that don't buy us anything". Then Java developers say "changing this int into a short doesn't make the object any smaller, so I might as well use the int for everything and not worry about overflow".
Maybe embedded JVMs are different, I don't know.
Patrick Doyle
I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
In my experience (over 30 years), the effort that has the best pay-back in terms of reducing the risk and difficulty of new and maintenance programming is to design suitable (meaning appropriate given the tools, project size, and staff skills) data structures and data handling techniques, and communicate them effectively. The communicating part is best done in writing and this can be in design documents, README files, or as comments in the code itself. I've noticed that as I've aged, I have changed from attempting to write complete formal, well-formatted documents (which you never get to finish), over to informal README files and ascii documentation. The goal being to get something in writing for the next poor guy that's going to have to work on the code.
Picking on comments and coding styles, in my opinion, is a sign of lack of understanding. Sure there are crappy programming styles, and it's a shame when everyone on the team writes in their own personal style, but that's missing the big picture. While it's annoying, it's usually a sign of a much larger problem, namely that there's no thought behind the code and it's all a big hack.
Much more effort should be spent on documenting the data and data structures. In fact, early in my career I once heard an old timer say that if you understand the data and can invent sensible subroutine and variable names, the code more or less writes itself.
---- It won't be as bad as you fear or as good as you hope, but it will take twice as long as you plan.
. . . by reading Microsoft Visual C++ .NET examples.
"I worked hard for it. I deserve it. And I have it," Campbell said. "It's all mine."
How can it possibly get messed up?
I imagine it's due to people having their editors set to different-sized tabs, or differing values of the "use real tabs" vs. "insert spaces for tabs" toggle. Someone can go ahead and "fix" the alignment problem so it looks right to him, but in someone else's editor it'll just look all messed up (and that person might end up "fixing it back").
Theoretically this could be cured if we had a standard (and everyone stuck to it!), as in theory comments would be great if no one ever let them get out of sync with the code, but the point is theory doesn't always pan out, and when a less error-prone, actually fool-proof, method is available (looking at the braces instead of the indentation/looking at the (self-documenting) code instead of the comments), that's much better to use.
We all strive for having comments that are synchronized with the code, and indentation that's not misleading, but ultimately they cannot be relied upon.
Attention zealots and haters: 00100 00100
Actually, I'm talking about the OP's point of writing clean, understandable code with good variable names.
Something you can do with Perl, if you so desired.
My point, which flew over your tiny little head, was that this wasn't an integral part of the language... but rather a style of coding that can be used in most languages.
Even Perl.
--Phillip
Can you say BIRTH TAX
Thus, this is acceptable:or this:but never this:There was a time when I didn't worry about this issue, but one day I spent hours debugging a problem in someone else's code (a Unix Appletalk implementation) that broke because a line of code had been added to the start of a loop body which didn't contain braces. Of course, this pushed the original loop body out of the loop! But because both were indented as if they were in the loop, and logically belonged there, it was a very subtle and difficult bug to track down.
Ever since that experience, I automatically use braces if the statement spans multiple lines. I don't ever want to have to debug something so stupid again.
Deven
"Simple things should be simple, and complex things should be possible." - Alan Kay
No offense, but this is the most retarded brace style I've ever seen. While you may think it looks good on paper, it's much harder to maintain. I've had the misfortune to be stuck maintaining such code, and invariably I find myself needing to insert a new statement at the start of a block, or delete the first statement in the block, or otherwise rearrange the statements. But you still need to keep the brace at the start of the block (and indent properly), so it becomes a real pain in the ass to modify the code now that line-oriented editing operations won't work.
It's just not worth it. The K&R brace style saves just as much room on paper or screen and remains maintainable. Moreover, proper indentation makes it quite easy to see where the blocks are -- there's no reason to highlight the braces by giving them a line of their own unnecessarily. (But Python takes it too far by eliminating the braces entirely.)
Deven
"Simple things should be simple, and complex things should be possible." - Alan Kay
Not all of us have the luxury of working in an environment with a good IDE :(
:)
Emacs will do it... I guess!
If not, then a few hundred lines of PERL
It's all good, though. I'll grant you probably are right. I haven't really had a long career or anything. Just needed to vent. Can't believe you took it that seriously though.
Well, it was way harsh! Perhaps I should not have taken it so seriously. Sorry.
By your argument, we might as well write code like this:The interesting part of the code is the part that implements the program logic. The braces are syntax, no more. They're not interesting and shouldn't be highlighted.
Also, if you want to comment out the conditional in K&R style, you don't have to comment out the ending brace; you can just add an opening one:That's not a compelling reason to put the brace on a line by itself.
Deven
"Simple things should be simple, and complex things should be possible." - Alan Kay
Its not about how easy it is to read. Any beginning programmer should be able to read it.
The issue is understanding it. Perhaps this piece of code is has drastic ramifications on some ancient code elsewhere which cannot be changed (ie. binary only) which may not be totally obvious. Perhaps, perhaps, perhaps. The point is, if there is some fact about the code not immediately obvious from reading the code itself, it needs to be stated. Very little code can be said to be self documenting in a very clear way.
Remember, its not about HOW the code does what it does. Its WHY.
> it's due to people having their editors set to different-sized tabs
Now this is exactly the attitude I don't understand. Every project must have a standard coding style. It's the job of whoever is in charge to provide one and to ensure it is followed by everyone touching the code. It is done during code reviews (which should also be mandatory, preferably for everyone, but at the very least for the new people), when conformance to the coding style must be a prerequisite to a checkin.
Everyone here seems to think that there is nothing to be done about the situation; that each team member should be allowed to do whatever he damn pleases, with no oversight. How are any of these people still in business?
If I were your project leader, I'd tell you exactly, in a comprehensive written policy, how you should format your code, whether you should use exceptions or returns, which documetation parser to target, and what sort of comments to write. Standards must exist, and they must be enforced. There is no room for opinions and preferences after the standard has been decided upon, because a standard, even a bad one, is better than a hodgepodge mixture of styles that results otherwise. You follow the standard or you're fired. Period.
This goes for open source projects as well. Whenever I'm running one, you don't contribute unless it's in the proper style. I might rewrite your patch if I think it's worth the effort, but usually the answer would be "no". Specify a standard and make sure all patches are reviewed by you or someone you trust for compliance with that standard.
Yes, I am angry; all this multiculturalism bullshit really pisses me off. Programming is not a "politically correct" occupation where you have to take into consideration people's feelings. If I'm on your team, I'll follow your standard, even if I dislike it, and make everyone else do the same. The code is either good or it isn't. If it isn't, you fix it, or get off my team.
Semi-colons do when the body of a loop is empty:
The fact that you're inside a conditional (or loop) is important, and made quite clear by proper indentation.
But you cannot always rely on proper indentation, as you admit you've experienced yourself in your immediately prior post: "But because both were indented as if they were in the loop, and logically belonged there, it was a very subtle and difficult bug to track down." The compiler looks at the braces, and so should you.
you don't have to comment out the ending brace; you can just add an opening one
I don't even have to do that:
If you really feel that braces should not be on a line by themselves, you should take that to its logical conclusion and advocate:Attention zealots and haters: 00100 00100
A man who wants nothing is invincible
Honestly, who cares what brace style K&R used in their 17+ year-old book.
I seem to remember these guys also peppered their code examples with one letter variable names and avoided checking array bounds like the plague. Almost every string handling example had a potential buffer overflow in it. Should we keep these practices too because K&R popularized them? Are K&R that infallible?
Anyway, here you go, directly from the book:
"The position of braces is less important (than indentation is), although people hold passionate beliefs. We have chosen one of several popular styles. Pick a style that suits you, then use it consistently." -- The C Programming Language, page 10.
Thanks K&R for your permission! BSD style it is!
I'm coding for maybe 10 years so I'm a newbie in your eyes. Still I find it better readable to have the braces in the same line with if and else.
And 1600x1200 will never fit on my 12inch Powerbook. But that's the size that fits in my backpack nicely. Thus I still have only 50 lines on my screen and I don't want these 50 lines filled with lines with a single brace.
b4n
Code comments I find worthless and distracting are statements of who wrote the code, what bug number it fixes, and when it was done. Often I find "mature" (ok, old) code is filled with this type of stuff. // 7/13/00 default conversion type is BCD
// 2.5
// MCW // MikeW
For example (from a random file from the system I work on now):
ConversionType = BCC_BCD;
Who CARES the on 7/13/00 this change was made! Often these type of comments may include version numbers of the product (better, but still bad). Even worse I'll see JUST version info/dates:
if (m_bSomeNewFlag)
Maybe this was helpful for the developer working on these v2.5 changes but don't leave these breadcrumbs around.
Names or initials are bad as well, especially bad when only used alone:
OK, thanks Mike W. for all your hard work!
One issue with this type of stuff is that it's hard to maintain. How do you tell where the code added on "7/13/00" ends? What if I change that line, or add code near it? Do I change the date? Add my name to that code? There's 1000's of lines w/o names on them, who wrote those, and who cares?
Also, how the system worked in the past and how it's been changed can seem, in theory, to be useful... but what is the real benefit? A history lesson? I feel the code is not the best place for this. Often these type of comments included the commented old code, which I find very distracting from what the code IS doing. Even worse is commented code w/ no explanation of why it was commented and not just removed outright - but that's a bit off topic.
The who's, what's, and when's of code changes should be tracked in your SOURCE CONTROL and BUG TRACKING system, period. If those two systems work together, all the better. If you don't have one that can do this job, get one. Make sure it's easy, people are trained on it, accessible to everyone, and fast.
This space intentionally left blank.
No, the { } are equivalent to
BEGIN
END
There is nothing to say what they are equivalent - we are free to interpret them in any way we choose.
As for indentation, if you have improperly indented code, it obscures the structure of the code. Braces alone don't really help visualize the code structure, it's the indentation that does it. Seeing the braces only serves as a confirmation. Try eliminating all indentation and newlines and rely on the braces alone to see where the blocks lie. Just how well does that work?
As for your form of commenting out an "if" block being easier, I didn't deny that it was. I just disputed the claim that you need to find the closing brace to comment it out. I don't think the ability to comment out the if conditional conveniently is sufficiently important to drive the decision of what brace style to use.
As for the "logical" conclusion of using this style:That style is just as bad as this style:The reasons are much the same. You can't operate on statements as lines anymore. If you insert, delete or rearrange lines where the brace is merged with a line of the block, you have to repair the brace, which is a major nuisance. If you keep the opening brace at the end of the "if" line, it never needs to move, so it's not an issue.
And I'm not advocating reserving a line for the closing brace. It's the end the "if" statement as a whole that calls for the newline after that closing brace. When "else" blocks are used, you merge the lines quite efficiently:That's certainly more space-efficient and easier to read than this annoying style:I'd rather read code using K&R's "One True Brace" style any day...
Deven
"Simple things should be simple, and complex things should be possible." - Alan Kay
And there's more to style than indenting, anyway.
Nope, you won't be able to avoid style decisions just because you use Python.
- David A. Wheeler (see my Secure Programming HOWTO)