Re: Coding style question

From: Neil Conway <neilc(at)samurai(dot)com>
To: korryd(at)enterprisedb(dot)com
Cc: imad <immaad(at)gmail(dot)com>, pgsql-hackers(at)postgresql(dot)org
Subject: Re: Coding style question
Date: 2006-11-02 19:49:26
Message-ID: 1162496966.5692.230.camel@localhost.localdomain
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Thu, 2006-11-02 at 14:23 -0500, korryd(at)enterprisedb(dot)com wrote:
> Yes, the compiler can detect unitialized variables,

In most situations, anyway.

> I've seen too many less-scarred developers add an " = NULL" to quiet
> down the tool. But that's (arguably) worse than leaving the variable
> uninitialized - if you simply initialize a variable to a known (but
> not correct) value, you've disabled the tool; it can't help you find
> improperly initialized variables anymore.

I definitely agree that this is not good style[1] -- if you see any
Postgres code that does this, I think it should be fixed. (This is
probably something you could teach a compiler to warn you about, as
well.)

> That's another reason I prefer initializers (and nested variable
> declarations) - I can put off creating the variable until I can assign
> a meaningful value to it.

Well, clearly you should only assign meaningful values to variables, but
I don't see anything wrong with omitting an initializer, initializing
the variable before using it, and letting the compiler warn you if you
forget to do this correctly. I agree with Greg's rationale on when to
include an initializer in a variable declaration (when the initializer
is trivial: e.g. casting a void * to a more specific pointer type, or
using one of the PG_GETARG_XXX() macros in a UDF).

> (I don't go so far as to introduce artificial scopes just for the sake
> of nesting variable declarations).

I don't introduce artificial scopes either. However, I do try to declare
variables in the most-tightly-enclosing scope. For example, if a
variable is only used in one branch of an if statement, declare the
variable inside that block, not in the enclosing scope.

I also find that if you're declaring a lot of variables in a single
block, that's usually a sign that the block is too large and should be
refactored (e.g. by moving some code into separate functions). If you
keep your functions manageably small (which is not always the case in
the Postgres code, unfortunately), the declarations are usually pretty
clearly visible.

-Neil

[1] http://advogato.org/person/nconway/diary.html?start=24

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Stephen Frost 2006-11-02 19:55:52 Re: Design Considerations for New Authentication Methods
Previous Message imad 2006-11-02 19:48:12 Re: Coding style question