416 points · by mohaps · 13y ago · 206 comments
http://google-styleguide.googlecode.com/svn/trunk/cppguide.x...
The author's first point about establishing conventions so that you can re-use the code that works with those conventions is very important. At Google, nobody writes code to serialize/deserialize bytes, because the default answer is just "use protobufs". Nobody writes low-level communication protocols (well, outside of some very-specialized infrastructure teams), because there's one RPC system. There's one standardized naming system, and a mostly-standard logs format and method for analyzing logs. If you do batch computation, there're two solutions, and there're only a handful of different file formats and storage engines, certainly less than in the open-source world.
I think Rails and Django (and Lisp) discovered the same principle: if you get everybody writing their code & data files the same way, you can write tools to manipulate those files, and that saves you way more in productivity than trying to get the perfect file format.
Logjammer/Treehorn: XMLRPC. (Yes, what a horrible project name. Juveniles.)
There are others. NIH actually happens inside the company too.
with the notable exception of lining up things horizontally, which tends to be frowned on.
Furthermore, this can generate horrible commits, for example:
int x;
int y;
becomes: int x;
int y;
float z;
after adding ONE single variable. But your commit will contain changes for the above 2 lines. This will make for an insane experience once your variable list grows to a certain size (including multiple spacing changes) and you intend to rollback/cherry-pick/time-warp. Then you will get to deal with the full wrath of conflict resolution. Also, your commit (of one logical line change) contains way to much meta info, which also decreases commit/diff readability. int x
int y
float z
I might add a blank line between x and y, too.If you do vertical alignment such that it emphasises semantic relations, you avoid commits that change more than they should, and it also helps draw your eye to relationships between variables.
Finally, a guru dares to call a spade a spade. Header-only, template-only C++ programming is a mistake! After 1995 C++ Standardization took the wrong path and lost contact with real world developers. The glorification and idolization of 'STL programming' was in sharp contrast with programmer's needs. Today in C++ there is a chasm like in no other language between the 'official language' and what programmers need and use day in day out.
And now a whole new generation of programmers can gaze at the horror of Modern C++ metaprogramming and conclude that metaprogramming is bad....
If you'd asked the standards body to add a turing complete type-level meta-programming language to C++ in order to generate code at compile time I suspect they'd have told you to get knotted.
What people actually asked for was a reasonable syntax for adding generic functions to C++ that would not carry any runtime cost. Sounds completely reasonable, right? The standards group said "sure, how about this?", and kept adding more perfectly reasonable individual requests to the syntax like template specialisation. Only afterwards did the true nature of crawling horror that they'd inadvertently unleashed become apparent.
Remember the STL is complicated because it tries to be super generic, and it tries to be super generic because it's a library so it tries to cater for all possible uses. If you're writing a program instead of a library, you can make things orders of magnitude simpler because you only have to provide what you need, not everything any programmer on Earth might need.
Java Swing using anonymous classes to 10 or more depths to represent callbacks because OOP and inheritance > all.
Haskell having one file IO operation a thousand feet below the surface of a program "un-purifying" the entire call stack with side effects because pure functional is king.
Trying to implement any generic anything in C, because in procedural having template or inheritance based polymorphic behavior is crazy, so you end up with 5 million ways to write readNumber() for every numeric type ever.
So go figure, procedural, meta, functional and OOP all go completely deep end when you try to kitchen sink them as the be all end all solution to all problems and woes.
And that's the way it should be. (Refator your programme, if you want to keep the other functions pure. But it is a Good Thing (TM), that you can not hide your IO if you pile on enough layers.) Haskell has other problems, though.
Yet now, the first example that I saw in this article hurts my eyes. Compare:
for ( i = 0; i < in->numVerts ; i++ ) {
dot = plane.Distance( in->verts[i] );
dists[i] = dot;
if ( dot < -LIGHT_CLIP_EPSILON ) {
sides[i] = SIDE_BACK;
} else if ( dot > LIGHT_CLIP_EPSILON ) {
sides[i] = SIDE_FRONT;
} else {
sides[i] = SIDE_ON;
}
counts[sides[i]]++;
}
Versus: for(i = 0; i < in->numVerts; i++)
{
dot = plane.Distance(in->verts[i]);
dists[i] = dot;
sides[i] = dot < -LIGHT_CLIP_EPSILON ? SIDE_BACK :
dot > LIGHT_CLIP_EPSILON ? SIDE_FRONT :
SIDE_ON;
counts[sides[i]]++;
}Conclusion: We have different preferences.
The ternary operator in general eases understanding because it extracts the common bit, i.e. "sides[i] =", meaning you don't have to carefully read the contents of each and every conditional block to verify nothing else is going on besides this one assignment.
It's a nice little oasis of Functional style in an otherwise pretty un-Functional language.
The only reason I was able to quickly understand your beautifully-aligned code was because I had read the logic in the previous block, which is stupidly-easy to parse.
I also (like many others) shun the use of nested ternary operators. Probably because I'm used to dealing with PHP's straight-up broken implementation.
Further, I'd have split the side being determined from the sides array, as it's rather mentally taxing to figure out the increment at the end:
if (dot < -LIGHT_CLIP_EPSILON) {
side = SIDE_BACK;
} else if ...
sides[i] = side;
counts[side]++;This is a great example of "factoring out" that satisfies both the computer science and the mathematical definitions of the term. The assignment "sides[i] = " is repeated inside the if block, and it can be "factored out" using the ternary operator, just like in math:
(a * x + a * y + a * z) = a * (x + y + z)
I'm even tempted to say that "assignment distributes over if", but that might be pushing the analogy too far. Any further and I might start thinking about monads, so I'll stop here.This example turns the code into something that appears more airy but in fact is much harder to understand due to extensive use of ? :.
I find that one of my own major steps toward programming maturity happened when I stopped doing goofy things like this and started writing code that was as simple as possible to logically follow, and that was as un-special-cased as possible. (By this latter I mean, if you change the code a little bit, you don't have to rewrite it; it looks basically the same. Imagine you want to do more than just assign one variable inside the clauses of the 'if'. In the Carmack version you just add more code there. In the proposed substitute, you have to rewrite the whole thing.)
If you want to do something in addition to assignment, it's really quite easy: Just add a new `if` block underneath. This clearly separates your conditional assignment from whatever else is going on that may or may not be related to the assignment. (What if you add something besides assignment to the if, but then want to change the conditions for only that? You have to rewrite the whole thing!)
The most egregious example of I can think of in this kind of thing is JS "gurus" who try to use the fewest semicolons possible in their unminified source. It doesn't add readability, and the semicolon rules are complicated enough that one could easily write a bug while trying to stick to the style.
Sometimes languages have "tricks" that aren't sharp, and those are OK to use when you know them, but one has to distinguish.
The ternary operator is used to guarantee assignment to a variable based on some condition. It's not only a way to save space, it's a way to express your intent clearer. It simply doesn't leave any undefined code path behind.
In your case of changing the code a bit, in the carmack version of the function there's a risk that you remove the assignment to sides[i] in one case and it will later be undefined.
Though i agree that the syntax is horrendous since it requires you to remember exactly what the symbols ? and : do. Compare to the much nicer and to a newbie understandable python syntax: x = y if c else z
"By this latter I mean, if you change the code a little bit, you don't have to rewrite it; it looks basically the same."
I'd say that's kind of the point though. The first one would look "basically the same" if in the last else it assigned to sides[j] instead of sides[i]. In the last one it would look very different if it was about "doing stuff" rather than choosing which value should go to sides[i].
You literally want to paint code, not write it. :)
for (int i = 0; i < in->numVerts; i++)
{
dot = plane.Distance (in->verts[i]);
dists[i] = dot;
sides[i] =
dot < -LIGHT_CLIP_EPSILON ? SIDE_BACK :
dot > LIGHT_CLIP_EPSILON ? SIDE_FRONT : SIDE_ON;
counts[sides[i]]++;
}
Note that emacs will tab-align the table rows properly if you break the sides[i] = line after the = which is why I did it; not sure about vim. sides[i] = dot < -LIGHT_CLIP_EPSILON
? SIDE_BACK
: dot > LIGHT_CLIP_EPSILON
? SIDE_FRONT
: SIDE_ON;
... sides[i] = dot < -LIGHT_CLIP_EPSILON ? SIDE_BACK
: dot > LIGHT_CLIP_EPSILON ? SIDE_FRONT
: SIDE_ON
;
This is a little cleaner if your values are longer, and has slightly nicer diffs if you add conditionals.Note that this won't work in many languages whose ternary operator precedence is different (PHP comes to mind).
"The major evolution that is still going on for me is towards a more functional programming style, which involves unlearning a lot of old habits, and backing away from some OOP directions."
http://www.altdevblogaday.com/2012/04/26/functional-programm...
This is a very good point that probably could be systematically exploited. Does anyone know examples of this?
import Control.Monad.ST
import Data.STRef
fact :: Int -> Int
fact n = runST (fact' n)
fact' :: Int -> ST s Int
fact' n = do a <- newSTRef 1
mapM_ (\x -> modifySTRef a (*x)) [1..n]
readSTRef a
Here the function `fact'` uses mutable variables (encoded in the use of `ST` in its type -- `ST` stands for State Thread) but the function `fact` is pure -- the call to `runST` ensures that none of the side effects leak out of `fact'`.As with most Haskell code, the types are optional - I included them for clarity.
I don't know what's his stance on the subject since though.
That wasn't for functional programming though. It was instead for the built-in static code analysis the Haskell type system and compiler provides.
If your description is accurate, Rust[1] is exactly what he wants. I've been learning Rust recently (with a little help from [2]) and it does a ton of static code analysis, is safe by default (no dangling or null pointers, no shared mutable state), uses Hindley-Milner type interface just like Haskell, and generally is what you would expect if Haskell and C++ had a baby.
http://gamasutra.com/view/news/169296/Indepth_Functional_pro...
http://www.reddit.com/r/haskell/comments/jap3x/im_very_tempt...
http://blogs.uw.edu/ajko/2012/08/22/john-carmack-discusses-t...
All too often, I've heard about some language, and then spent minutes trying to figure out what it is all about.
Rust is definitely worth a longer look by me.
Most functions have a huge blob of variable declarations right at the top, as was once necessary in C, even though these variables aren't used until later, or possibly even at all. Usage of const is minimal to non-existent. Global variables are everywhere.
It made some of the functions I had to modify so hard to read that I wound up completely editing them, particularly those variable-declaration blocks, even though I ultimately only needed to change a line or two to get my mod to work.
void up_front_decls()
{
float some_var;
int another_var;
some_var = get_some_var();
do_some_calculations(some_var);
maybe_something_else(&some_var);
some_var = get_another_var();
do_some_other_calculations(another_var);
blah_blah_already_broken();
}
void as_needed_decls()
{
float some_var = get_some_var();
do_some_calculations(some_var);
maybe_something_else(&some_var);
int some_var = get_another_var();
// compile-time error
// ...
}
Also: void poor_style()
{
up_front declarations;
also encourage;
this_ridiculous *block_style;
that_is a_royal_pain;
to maintain;
because_some_long_type inevitably;
screws_it up;
}:Tab /\S\s\zs[ ]\S*
Explanation: \S\s* finds a non whitespace character followed by as many whitespace characters as possible. This brings us to the beginning of the variable name. We then use \zs which says that the "found" area should only begin here.
Since we want the * in block_style to be attached to the indented word but not before the variable name, we match either * or space followed by a non-whitespace character to symbolize the beginning of the word. End result:
void poor_style()
{
up_front declarations;
also encourage;
this_ridiculous *block_style;
that_is a_royal_pain;
to maintain;
because_some_long_type inevitably;
screws_it up;
}If your function is five pages long, and in the fifth page you can't remember what's in scope and you have to reread through the entire function above, it might seem that having all variable declarations at the top would help, because you'd only have one place to look at. But the real problem there is that the function is too long, and it should be refactored instead.
I most certainly am const pedantic as well, and I was back when I worked on this project, too -- quite a few of the "inconsequential" lines I checked in were simply moving a variable declaration down to where it was initialized, and adding 'const'. I found the resulting code much easier to read.
If instead, a variable is assigned to only when it is defined, you're moving (in a small way) towards functional programming.
Also, I often use scope just control the lifetime of a resource. These look like meaningless braces in the middle of a function to the uninitiated. It's RAII.
You can't do that unless you look at the assembly output. While there may have once been a time in history where "locally-scoped variable == entry on stack", those days are long gone. Any decently smart compiler (i.e. GCC and LLVM) will use registers in preference to the stack, and will collapse local variables whose lifetimes do not overlap into a single storage location.
const int x = foo();
// ...
const int y = bar(x);
and also have your variables all declared at the top.In C++ I'm a const nazi and declare where used to facilitate it, but if I'm writing C that targets the MSVC compiler (C89) where all variables have to be collected at the top of the inner scope I'll relax this as much as I have to.
There's two things here that irk me a little bit:
the stream operator overloading - maybe I have been writing C++ for many years, but I can't get behind using printf vs. stringstream because << is a 'bastardization';
public variables because you don't like adding accessor/mutator methods.
Other than those two everything else is a stylistic preference that I mostly agree with. Statement braces around control blocks should absolutely be a requirement as well as pedantic const.
But would you agree that the practices mentioned in the article are what the team got right? You can remove the author's gushing about the code's beauty and have a substantive article left. For instance, the section on vertical spacing had me reconsidering my own style. The discussion of method signatures seemed pretty solid, too.
Besides that, I think the stylistic changes this author is commenting on are fairly minor. I think the conciseness of vertical space was a bit confusing sometimes; this article only shows the simple functions where it works. The almost complete absence of templated is more likely because no STL code was used.
Certainly, the code base is very thorough. When I realized I had to use quaternions to represent the player's orientation in the game space, there was already an idQuat class ready and waiting and fully functional, which was very nice. I think that idQuat class was never even used anywhere in the base code, so it was cool -- for someone with who never knew about quaternions before then -- to have a class fully implemented and ready for me to use.
Immutability...one less thing to worry about.
Broadly, my feeling is that getting your own APIs (internal and external) to be const correct is important and worth the trouble. But don't jump through hoops to shoehorn the strategy into someone else's code where it isn't honored.
If you're building a program in any language and it interacts heavily with a particular library then you'd better write something idiomatic to that library. If you're going to be using several libraries (including your language's standard lib) with different idioms then one of the most important design decisions you can make is how to bridge them, and where to make compromises.
Mathematical thesis are using a syntax arguably much much more powerful than programming languages and yet they're still using lots and lots of english to describe what the formulas are doing and why they're (supposedly) correct in doing so.
I very much prefer to have 1000 lines of some Lisp dialect with lots of comments about what the code does than 10 000 lines of "self-explaining" Java/C# code.
Code can contain bugs. Comments cannot.
I disagree. While the comments won't break your code, they can certainly ease the introduction of bugs, and cause cognitive delays when they're wrong or out of date.
Comments need as much care as the code itself, with the DRY principle guiding when they need to be pruned.
I never liked templates myself, and still avoid them almost completely. Even if my reasons are ridiculous, here they are:
1) I typically don't use anything where I don't understand its inner workings (i.e. how it manages memory, how the compiler is likely to optimize it). This does not mean the entity in question is bad, it just means I'm too lazy to learn about it on a deeper level.
2) In most cases where I need to handle a diverse amount of operations and a diverse amount of data types, it is not CPU-critical and I can resort to a higher level scripting language that is much better suited for the purpose.
3) Template syntax does not sit well with me. This is really just an OCD on my end.
4) I often prefer using uber-types (all-encompassing) to many different types -- within reason. I don't like to extend classes for this reason (particularly when you get into extension-hell with 5 different sub types).
#4... I think that might make a lot of sense with a weak or dynamic type system, but with a static type system there is a lot of benefit to having a different type anytime the behaviour is different. Of course, that can be tedious unless you have templates or at least generics...
The author makes a good point that comments are just more text that you need to maintain, and whenever you make changes you now have to make changes in two places: in the code, and in the comment - (and I guess in the unit tests as well, depending on the change...)
The best code I've personally seen has been code with no comments and an attached document explaining how the system works and how modules tie together.
Clarity can usually be addressed with longer variable or method names, but there's a strong culture against that in nearly ever programming community.
It would be interesting to see a list of those that discourage long method and variable names. I haven't seen anything that suggests that Java, Ruby, Python, Haskell, Kotlin, Scala, PHP, Groovy etc. discourage long variable and method names.
// Toggle between Dropdown and Text
if(_protected.fields[field].fieldType() === "Dropdown") {
_protected.fields[field].set("fieldType", "Text");
} else {
_protected.fields[field].set("fieldType", "Dropdown");
}
I think it would take me about 4 seconds to figure out that this code "toggles between Dropdown and Text" if the comment weren't there. Since the comment is there, I can just glance at the code and understand immediately what it does. toggleDropdown(field) {
if ...
}
toggleDropdown(_protected.fields[field]);
Also the external documentation wouldn't have anything like this in it. It would be pretty much: UI Code is in XXX. It communicates with ZZZ using YYY.
Fields in the UI are changed between text and dropdowns
depending on the value in the database that comes
from ZZZ. etc.I am asking because I've only used gofmt to format Go code and infact it was gofmt which introduced the whole concept to me.
http://astyle.sourceforge.net/notes.html
I think Go is pretty unusual in that gofmt is provided with the language. So all Go everywhere looks the same. It's awesome isn't it? :)
By concrete I mean what changed in Id's code (or some other game or ui framework), and not just some text book example. What changed in GameObject or PhysicsSphereObject or RenderableSkinnedMesh or whatever things changed. What did the code used be like? What was changed? What benefits did the change provide? What problems did the change introduce?
Abstract talk is interesting but "show me the Money!" ;-)
Yes, technically they have different motivations for going the way they go, but the end results tend to coincide neatly :)
What I find much harder is to write "beautiful" code at a higher level. The examples shown are mostly algorithms working with fundamental language features. My code tends to get ugly when integrating APIs from different sources with different conventions. I spend a lot of time checking return codes, mapping from one set of error codes to another. Sometimes it's hard to decide whether a return code has to be checked or whether I should assume, for efficiency, that all parameters I'm sending in or getting out are ok.
Other things that uglify my code: exception handling, locks or other concurrency artifacts, retry loops.
My second programming lecturer ever, refused to correct my assignments if these rules were not followed. He never told us said rules though. This was before I learned what an array was! Got 0% on my first two assignments with him but eventually he corrected the next ones with a good life lesson.
Frankly its the only thing I remember from that asshole but was probably one of the most important lessons in my opinion!
I always resent doing it but I can see how if the body of the function is not declared in the header file, but instead the associated .cpp file, that an author can change it, without introducing a whole recompile overhead.
Writing code that may not be needed is bad, but it's a trade off vs. preventing other users writing code that depends on it when their code should not.
I mean, isn't that like not giving a sh-- about encapsulation principles ?
I then just say, change it when you need it, and use that fancy "find usages" thing most IDEs and vim have.
The article makes it sound a little like you can just slap const everywhere and your code will be better. It does take more time and effort to be const correct, although it's usually worth it.
common->Frame(){ session->Frame() { ... } }
etc.