Coding standards and readable code (response to Charles)

I’m responding off-issue to Charles here, who dove into
deep waters in a pull request…

declare variable right before it gets used, as oppose to at the top of the function.

This is important for readability. Keeping things
as local as possible is the principle. We can only really
grasp code in small-ish chunks, so when variable declarations
are far from where they’re used, there’s mental bookkeeping
overhead you don’t have if they’re right there. This is
one of the reasons preserving vertical space is so important,
too—you want to be able to see everything you need on the

Intended Effect:

• Code readability

This is critical for reasons Daniel mentioned—code gets
read a lot and maintainability is largely about having
readable code.

The reading level we’re going for, if you will, is someone
who is fluent in C++. We can’t explain the language in comments
as we go!

• Memory isn’t allocated for a variable that only get’s used later

Don’t know what this means.

• Aesthetics


How to Verify:

The first two intended effects are trivial. Code doesn’t break.
The question of aesthetics is considerably more complicated and profound. What is beauty, and more importantly what is it in the framework of Stan, where only computer scientists seem to grasp it?

There are actually books written on beautiful code, but asking
what it is does seem much deeper — like asking what a beautiful
city is. Part of it’s look and feel, part of it’s usability.
Definitely part of what makes code beautiful is being
easy to read. But more importantly, being easy to understand, which
is more conceptual. Being easy to understand means hewing to the
conventions of the programming language.

One thing I can recommend that really shaped my and Daniel’s
aesthetics is Fowler’s Refactoring (Java) and the "gang of four"
patterns book (C++) about higher-level designs. That and
Hunt and Thomas’s Pragmatic Programmer. Read all those, and you’ll
be thinking much more like a software engineer (our problems
are almost all engineering related, not scientific).

  • Bob
1 Like