Coding standards

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Natt Serrasalmus

    #1

    Coding standards

    After years of operating without any coding standards whatsoever, the
    company that I recently started working for has decided that it might be a
    good idea to have some. I'm involved in this initiative.

    Typically I find that coding standards are written by some guy in the
    company who has a way of coding that he likes and then tries to force
    everybody else to write code the way he likes it, not for any rational
    reason, but simply for the subjective way he likes it. I think this is
    wrong.
    This is particularly irksome when it comes to issues of code layout style
    which has very little relevance to the execution of the code or the
    readablility and maintenance of the code.

    I also think it is wrong for coding standards to try to prevent idiots from
    doing stupid things. No matter how stringent some standards are, somebody
    stupid is going to find a way to do something stupid to the code. My point
    is that instead of making the standard more restrictive on good coders, the
    bad coders should be brought up to speed to be able to write good code, not
    pandered to by the standard. For example there is the seemingly universal
    attitude that fully bracketed
    syntax is the way to go (this will stop the idiots). I strongly disagree.
    There are many times that leaving out the braces where not necessary makes
    for more readable code. It also reduces the maintenance of braces; the fewer
    braces the easier it is to keep braces matched up. The problem is that I
    think most coders are too lazy to be bothered to know exactly when they need
    braces and when they don't. If you don't know, just stick them in everywhere
    that it can't hurt. Lots and lots of braces means lots and lots of code to
    maintain that doesn't need to be there.

    I recently read a standard that prohibited use of the ternary (conditional
    ?) operator. I find that most C programmers just haven't bothered to learn
    how to use it and don't want others to use it, because then they'll have to
    figure it out. However I have also found that in most cases where it is
    used, it can make the code much clearer even for those who are not
    accustomed to its use.

    a = (b == c) ? d : e;

    Is just as understandable and more maintainable than

    if (b==c) {
    a = d;
    }
    else {
    a = e;
    }

    In the first case it is obvious in one line that you are simply assigning a
    value to a based on the condition. The use of the if statement makes for a
    lot more code that is subject to error in maintenance.

    Another issue that I have come across is the one way out of a function
    issue. I contend that if there are conditions that warrant an earlier exit
    from a function then the early exit should be taken. For eample:

    int funct( int arg )
    {

    .....

    if (condition) return ERROR;

    ....

    return OK;

    is much better than

    int funct( int arg )
    {
    int retval = ERROR;
    .....

    if ( !condition) {
    retval = OK;
    (rest of function);
    ....
    } /* end of if ( !condition) */

    return retval;

    In the first case you've been very clear as to what values are going to be
    returned, you've reduced the number of braces involved and you've reduced
    the indentation level of the major part of the function. The argument
    against this is that there may be some clean up that needs to be done in a
    function and this style may lead an idiot to exit the function with out
    doing the clean up. My rebuttal is that number one, only a small minority of
    functions have the requirement that the clean up be done before exiting the
    function. Number two, the clean up should be a separate function anyway that
    can be called from anywhere in the parent function and number three you just
    can't count on the standard to protect the code from idiots anyway so why
    pretend that it does?

    A similar issue is this one:

    if (condition) {
    retval = func(arg );
    }

    If that condition has to be tested before each function then the condition
    should be evaluated by the function instead:

    retval = func( arg, condition);

    ....
    int func( int arg, BOOLEAN condition)
    {

    if (!condition) return OK;

    ....
    }


    On the whole I consider less code to be more maintainable than lots of code.
    Anywhere I can reduce the lines of code then that makes it easier to
    maintain. For example:

    if( condition)
    {
    retval = func( a, b);
    }
    else
    {
    retval = func( a, c);
    }

    if (retval != OK)
    {
    error_exit_func ();
    }

    a much better way is

    if ( !func(a, condition ? b : c ) error_exit_func ();


    Is there anybody out there who will agree with me on these issues or am I
    the lone voice for this type of coding?






  • Michael Mair

    #2
    Re: Coding standards

    Natt Serrasalmus wrote:[color=blue]
    > After years of operating without any coding standards whatsoever, the
    > company that I recently started working for has decided that it might be a
    > good idea to have some. I'm involved in this initiative.
    >
    > Typically I find that coding standards are written by some guy in the
    > company who has a way of coding that he likes and then tries to force
    > everybody else to write code the way he likes it, not for any rational
    > reason, but simply for the subjective way he likes it. I think this is
    > wrong.[/color]

    Well, from the rest of your post one could get the impression
    that you are just a more self-aware flavour of "this guy".
    Your examples show preferences which may be more restrictive
    for some programmers than other coding standards.

    [color=blue]
    > This is particularly irksome when it comes to issues of code layout style
    > which has very little relevance to the execution of the code or the
    > readablility and maintenance of the code.[/color]

    This is correct. Sooner or later someone will become coding police
    more interested in the right use of indentation, white-spaces,
    comment styles and so on.
    However, having had the dubious pleasure of coding in a group
    where people did not care about the "details", I think that coding
    rules which can be scribbled down on one piece of paper are the
    best way to go. If you use cvs, even stuff like indentation can
    be important enough to be put down on said sheet.

    [color=blue]
    > I also think it is wrong for coding standards to try to prevent idiots from
    > doing stupid things. No matter how stringent some standards are, somebody
    > stupid is going to find a way to do something stupid to the code. My point
    > is that instead of making the standard more restrictive on good coders, the
    > bad coders should be brought up to speed to be able to write good code, not
    > pandered to by the standard. For example there is the seemingly universal
    > attitude that fully bracketed
    > syntax is the way to go (this will stop the idiots). I strongly disagree.
    > There are many times that leaving out the braces where not necessary makes
    > for more readable code. It also reduces the maintenance of braces; the fewer
    > braces the easier it is to keep braces matched up. The problem is that I
    > think most coders are too lazy to be bothered to know exactly when they need
    > braces and when they don't. If you don't know, just stick them in everywhere
    > that it can't hurt. Lots and lots of braces means lots and lots of code to
    > maintain that doesn't need to be there.[/color]

    If your company does not use editors which can keep up with braces,
    then they may be in trouble...
    Honestly, even though "full bracing" is unnecessary, this is one of
    the rules which depend on the rest of your coding standard. If there
    are no rules about indentation and brace placement or related issues,
    the belt and braces (no pun intended) method may be safer.

    [color=blue]
    > I recently read a standard that prohibited use of the ternary (conditional
    > ?) operator. I find that most C programmers just haven't bothered to learn
    > how to use it and don't want others to use it, because then they'll have to
    > figure it out. However I have also found that in most cases where it is
    > used, it can make the code much clearer even for those who are not
    > accustomed to its use.
    >
    > a = (b == c) ? d : e;
    >
    > Is just as understandable and more maintainable than
    >
    > if (b==c) {
    > a = d;
    > }
    > else {
    > a = e;
    > }
    >
    > In the first case it is obvious in one line that you are simply assigning a
    > value to a based on the condition. The use of the if statement makes for a
    > lot more code that is subject to error in maintenance.[/color]

    Well, this depends. I would have placed the parentheses differently,
    someone else might leave them out, a third might add all sorts of
    parentheses.
    However, banishing part of the language's operators or keywords is
    only advisable in very special cases. I would be very wroth if
    "for" and "do" were disallowed.

    [color=blue]
    > Another issue that I have come across is the one way out of a function
    > issue. I contend that if there are conditions that warrant an earlier exit
    > from a function then the early exit should be taken. For eample:
    >
    > int funct( int arg )
    > {
    >
    > ....
    >
    > if (condition) return ERROR;
    >
    > ...
    >
    > return OK;
    >
    > is much better than
    >
    > int funct( int arg )
    > {
    > int retval = ERROR;
    > ....
    >
    > if ( !condition) {
    > retval = OK;
    > (rest of function);
    > ...
    > } /* end of if ( !condition) */
    >
    > return retval;
    >
    > In the first case you've been very clear as to what values are going to be
    > returned, you've reduced the number of braces involved and you've reduced
    > the indentation level of the major part of the function. The argument
    > against this is that there may be some clean up that needs to be done in a
    > function and this style may lead an idiot to exit the function with out
    > doing the clean up. My rebuttal is that number one, only a small minority of
    > functions have the requirement that the clean up be done before exiting the
    > function. Number two, the clean up should be a separate function anyway that
    > can be called from anywhere in the parent function and number three you just
    > can't count on the standard to protect the code from idiots anyway so why
    > pretend that it does?[/color]

    You are once more only advocating your own views.
    Why not formulate a rule which allows only single exit points
    for functions containing cleanup code. Whether this is reached
    by state variables, goto or splitting the function into three parts
    (initialization , work, cleanup) such that the rule only aims at
    the actual cleanup routine, can be up to the programmers and
    situation.

    [color=blue]
    > A similar issue is this one:
    >
    > if (condition) {
    > retval = func(arg );
    > }
    >
    > If that condition has to be tested before each function then the condition
    > should be evaluated by the function instead:
    >
    > retval = func( arg, condition);
    >
    > ...
    > int func( int arg, BOOLEAN condition)
    > {
    >
    > if (!condition) return OK;
    >
    > ...
    > }[/color]

    Perfectly valid for this case. But if func already has seven
    parameters, then you are probably doing yourself a disservice
    by adding another one or two -- people will just get "blind"
    with respect to the arguments.
    Given your liking for short expressions you might just go for
    condition && (retval = func(arg))

    [color=blue]
    > On the whole I consider less code to be more maintainable than lots of code.
    > Anywhere I can reduce the lines of code then that makes it easier to
    > maintain. For example:
    >
    > if( condition)
    > {
    > retval = func( a, b);
    > }
    > else
    > {
    > retval = func( a, c);
    > }
    >
    > if (retval != OK)
    > {
    > error_exit_func ();
    > }
    >
    > a much better way is
    >
    > if ( !func(a, condition ? b : c ) error_exit_func ();[/color]

    Apart from the missing closing parenthesis, I think
    that is too much. I would at least let the call to
    error_exit_func () reside on a second line.

    [color=blue]
    > Is there anybody out there who will agree with me on these issues or am I
    > the lone voice for this type of coding?[/color]

    Probably you will find some people who will agree with most
    you said.

    Without knowing the type and complexity of the code, one usually
    can cobble together exactly what you proposed: A coding standard
    fitted to the tastes of the creators.

    I suggest you start from the purpose of the code and the needed
    documentation level.
    Then add rules like naming conventions for certain types of objects,
    unified interfaces (source, destination, size or destination, source,
    size or source, size, destination or ...)
    If there is still some room on your sheet of paper, state rules
    like "code such that it can be read like prose, avoiding inane
    comments". Be specific about comment styles.
    If there is still room for more rules, have a look at the bugs
    which cost most time to find. Enforcing rules which reduce the
    number of these bugs are a good idea. If this means that every
    new module gets unit tests, so be it.
    If there is still room for more rules, you cheated and went for
    toilet paper...

    Do not go for rules aiming at whatever makes you itch.
    Go for the problems.
    Reasons for the above order: If clear documentation is required,
    bugs are found sooner, and people who invest enough thought
    before coding automatically code in a less convoluted way.
    Unified interfaces and naming rules save time.
    Weeding out the "fit the quota" comments or other bad habits
    by general rules is more effective than trying to cover all
    positive good comment/bad comment situations.
    If there is a pattern of how bugs get into the code breaking
    it helps more than arguing about the intricacies of brace
    placement. If you cannot find such rules, then you have found
    the point in your software where redesign or alternative
    solutions are needed...


    HTH
    Michael
    --
    E-Mail: Mine is an /at/ gmx /dot/ de address.

    Comment

    • Bart Goeman

      #3
      Re: Coding standards

      Op Sun, 19 Dec 2004 18:05:06 -0500, schreef Natt Serrasalmus:
      [color=blue]
      > After years of operating without any coding standards whatsoever, the
      > company that I recently started working for has decided that it might be a
      > good idea to have some. I'm involved in this initiative.
      >
      > Typically I find that coding standards are written by some guy in the
      > company who has a way of coding that he likes and then tries to force
      > everybody else to write code the way he likes it, not for any rational
      > reason, but simply for the subjective way he likes it. I think this is
      > wrong.[/color]

      i think an arbitrary decision is (often) right.
      that's what standards are all about, uniformity.
      e.g. i would have liked that processor vendors had made a decision on
      endianness, little or big, and everyone would conform to that standard.

      maybe in some circumstances the other convention would be more usefull
      (?), but the advantage of having one endianness would be _very_ big indeed!

      i don't like these coding standard myself, everyone should code the way I
      do :-)
      [color=blue]
      > if ( !func(a, condition ? b : c ) error_exit_func ();[/color]
      IMHO this is too short. readability is very important. it should be
      easy even for novice programmers.
      but if novice programmers don't know ( ? : ) they should learn it instead
      of prohibiting it in the coding standard

      Comment

      • Gordon Burditt

        #4
        Re: Coding standards

        >After years of operating without any coding standards whatsoever, the[color=blue]
        >company that I recently started working for has decided that it might be a
        >good idea to have some. I'm involved in this initiative.[/color]

        Most coding standards, if applied in the same way as an employee
        dress code, would amount to something like "all employees shall
        wear a size 6 red dress catalog # AC37626R from Macy's during working
        hours" with no exceptions for the men or the pregnant.

        Please consider that there are things that are not worth spending
        a lot of time standardizing, such as the positioning of braces,
        except to agree that outdenting is awful:

        #include <stdio.h>
        #include <stdlib.h>
        int main(int argc, char **argv) {
        if (argc < 2) {
        printf("Usage: bulrfl filename\n");
        }
        exit(0);
        }

        [color=blue]
        >Typically I find that coding standards are written by some guy in the
        >company who has a way of coding that he likes and then tries to force
        >everybody else to write code the way he likes it, not for any rational
        >reason, but simply for the subjective way he likes it. I think this is
        >wrong.[/color]

        If you wish to standardize code layout, the best standard I can
        think of is "All C code shall be run through GNU indent with the
        following options before being checked into the source code control
        system." (I really don't care what options you choose, as long as
        outdenting is not selected, and I'm pretty sure it's not even
        supported. If necessary, select which options are used by coin
        flipping). Some source code control systems can even be made to
        do this automatically.
        [color=blue]
        >This is particularly irksome when it comes to issues of code layout style
        >which has very little relevance to the execution of the code or the
        >readablility and maintenance of the code.
        >
        >I also think it is wrong for coding standards to try to prevent idiots from
        >doing stupid things. No matter how stringent some standards are, somebody
        >stupid is going to find a way to do something stupid to the code. My point
        >is that instead of making the standard more restrictive on good coders, the
        >bad coders should be brought up to speed to be able to write good code, not
        >pandered to by the standard. For example there is the seemingly universal
        >attitude that fully bracketed
        >syntax is the way to go (this will stop the idiots).[/color]

        I agree with braces being used even where optional (e.g. in an if) but
        not for the reason "this will stop the idiots". I think it makes
        it more readable.
        [color=blue]
        >I strongly disagree.
        >There are many times that leaving out the braces where not necessary makes
        >for more readable code. It also reduces the maintenance of braces; the fewer
        >braces the easier it is to keep braces matched up.[/color]

        If by "matched up", you mean indented at the same level, let GNU
        indent handle it. If you mean unbalanced, then leaving them out
        is not going to help much, as you won't be any more consistent about
        leaving both out as putting both in.
        [color=blue]
        >The problem is that I
        >think most coders are too lazy to be bothered to know exactly when they need
        >braces and when they don't. If you don't know, just stick them in everywhere
        >that it can't hurt. Lots and lots of braces means lots and lots of code to
        >maintain that doesn't need to be there.[/color]

        If braces are "lots and lots of code", I think the code has a lot
        more problems than braces.
        [color=blue]
        >I recently read a standard that prohibited use of the ternary (conditional
        >?) operator. I find that most C programmers just haven't bothered to learn
        >how to use it and don't want others to use it, because then they'll have to
        >figure it out. However I have also found that in most cases where it is
        >used, it can make the code much clearer even for those who are not
        >accustomed to its use.
        >
        >a = (b == c) ? d : e;
        >
        >Is just as understandable and more maintainable than
        >
        >if (b==c) {
        > a = d;
        >}
        >else {
        > a = e;
        >}[/color]

        I especially find it useful in certain debugging situations:

        printf("Name: %s Address: %s\n",
        (name == NULL) ? "(null)" : name,
        (addr == NULL) ? "(null)" : addr );

        where the introduction of temporary variables or replicating the
        printf() is undesirable. It makes relating the %s and the argument
        that's guaranteed not to be NULL easier.

        When you've started nesting ?:, though, you've probably gone too far.
        [color=blue]
        >In the first case it is obvious in one line that you are simply assigning a
        >value to a based on the condition. The use of the if statement makes for a
        >lot more code that is subject to error in maintenance.[/color]
        [color=blue]
        >Another issue that I have come across is the one way out of a function
        >issue. I contend that if there are conditions that warrant an earlier exit
        >from a function then the early exit should be taken. For eample:[/color]

        Generally, I agree here, because you end up with deeper-nested
        conditionals, and near the end of the function, you have to look
        carefully to see what error conditions you don't have to worry
        about because you've already checked them.
        [color=blue]
        >int funct( int arg )
        >{
        >
        >....
        >
        >if (condition) return ERROR;
        >
        >...
        >
        >return OK;
        >
        >is much better than
        >
        >int funct( int arg )
        >{
        >int retval = ERROR;
        >....
        >
        >if ( !condition) {
        > retval = OK;
        > (rest of function);
        >...
        >} /* end of if ( !condition) */
        >
        >return retval;
        >
        >In the first case you've been very clear as to what values are going to be
        >returned, you've reduced the number of braces involved and you've reduced
        >the indentation level of the major part of the function. The argument
        >against this is that there may be some clean up that needs to be done in a
        >function and this style may lead an idiot to exit the function with out
        >doing the clean up. My rebuttal is that number one, only a small minority of
        >functions have the requirement that the clean up be done before exiting the
        >function. Number two, the clean up should be a separate function anyway that[/color]

        Cleanup can hardly ever be in a separate function because of all
        the local variables involved. It really doesn't make much sense
        to define a separate function with arguments of 7 pointers to free
        if they were allocated and 2 open FILE *'s to close if they were
        open. On the other hand, there is some use for closeifopen() defined
        below if you are careful to initialize FILE *'s to NULL and set
        them to NULL after closing a file. Now with memory allocation, you
        don't need freeifallocated () since free() itself does the same thing.
        [color=blue]
        >can be called from anywhere in the parent function and number three you just
        >can't count on the standard to protect the code from idiots anyway so why
        >pretend that it does?
        >
        >A similar issue is this one:
        >
        >if (condition) {
        > retval = func(arg );
        >}
        >
        >If that condition has to be tested before each function then the condition
        >should be evaluated by the function instead:
        >
        >retval = func( arg, condition);[/color]

        This depends on how the condition and the function are related.
        If, for example, func is actually fopen(), and condition is whether
        transaction logging is enabled, I can't see combining those into one
        function. On the other hand, I can see defining

        void closeifopen(FIL E *arg)
        {
        if (arg != NULL)
        {
        fclose(arg);
        }
        return;
        }

        because the condition is related to whether you can successfully
        execute the function at all, not some unrelated reason as to
        why you might or might not want to execute it.
        [color=blue]
        >...
        >int func( int arg, BOOLEAN condition)
        >{
        >
        >if (!condition) return OK;
        >
        >...
        >}
        >
        >
        >On the whole I consider less code to be more maintainable than lots of code.
        >Anywhere I can reduce the lines of code then that makes it easier to
        >maintain.[/color]

        Lines of code are a ridiculous metric, and you shouldn't use it.
        A good coding standard will forbid counting lines of code for any
        reason. Taking it to the extreme, all consecutive non-preprocessor
        statements go on the same line until you hit line length limits.
        [color=blue]
        >For example:
        >
        >if( condition)
        >{
        > retval = func( a, b);
        >}
        >else
        >{
        > retval = func( a, c);
        >}
        >
        >if (retval != OK)
        >{
        > error_exit_func ();
        >}
        >
        >a much better way is
        >
        >if ( !func(a, condition ? b : c ) error_exit_func ();[/color]

        No, I don't agree this is BETTER, and I think translating from the
        first case to the second is a BUG. Who said OK is equal to zero?
        Oh, yes, you're also missing a ).

        But this really sucks:
        if(condition){r etval=func(a,b) ;}else{retval=f unc(a,c);}if(re tval!=OK){error _exit_func();}
        [color=blue]
        >Is there anybody out there who will agree with me on these issues or am I
        >the lone voice for this type of coding?[/color]

        I'll go along with you as far as translating the first part to
        retval = func(a, condition ? b : c);

        Gordon L. Burditt

        Comment

        • Chris McDonald

          #5
          Re: Coding standards

          >>After years of operating without any coding standards whatsoever, the[color=blue][color=green]
          >>company that I recently started working for has decided that it might be a
          >>good idea to have some. I'm involved in this initiative.[/color][/color]


          Pleasing to see a helpful and sensible discussion here without a flurry of
          vitriolic comments claiming it to be off-topic (perhaps it's just a matter
          of the weekend or timezones).

          --
          Chris,

          Comment

          • E. Robert Tisdale

            #6
            Re: Coding [style] standards

            Natt Serrasalmus wrote:
            [color=blue]
            > After years of operating without any coding standards whatsoever,
            > the company that I recently started working for has decided that
            > it might be a good idea to have some. I'm involved in this initiative.
            >
            > Typically, I find that coding standards are written
            > by some guy in the company who has a way of coding that he likes
            > and then tries to force everybody else to write code the way he likes it,
            > not for any rational reason, but simply for the subjective way he likes it.[/color]

            Are you that guy?
            [color=blue]
            > I think this is wrong.[/color]

            Yes, but are you that guy?
            [color=blue]
            > This is particularly irksome when it comes to issues of code layout style
            > which has very little relevance to the execution of the code or the
            > readablility and maintenance of the code.[/color]

            You need to distinguish between *style* issues
            and good programming practice.
            [color=blue]
            > I also think [that] it is wrong for coding standards
            > to try to prevent idiots from doing stupid things.[/color]

            I don't think it's wrong.
            I just don't think it works.
            [color=blue]
            > No matter how stringent some standards are,
            > somebody stupid is going to find a way to do something stupid to the code.
            > My point is that instead of making the standard more restrictive on good coders,
            > the bad coders should be brought up to speed to be able to write good code,
            > not pandered to by the standard.
            > For example, there is the seemingly universal attitude that fully bracketed
            > syntax is the way to go (this will stop the idiots). I strongly disagree.
            > There are many times that leaving out the braces where not necessary makes
            > for more readable code. It also reduces the maintenance of braces; the fewer
            > braces the easier it is to keep braces matched up. The problem is that I
            > think most coders are too lazy to be bothered to know exactly when they need
            > braces and when they don't. If you don't know, just stick them in everywhere
            > that it can't hurt. Lots and lots of braces means lots and lots of code to
            > maintain that doesn't need to be there.
            >
            > I recently read a standard that prohibited use of the ternary
            > (conditional ?:) operator. I find that most C programmers
            > just haven't bothered to learn how to use it and don't want others to use it,
            > because then they'll have to figure it out. However, I have also found that
            > in most cases where it is used, it can make the code much clearer
            > even for those who are not accustomed to its use.
            >
            > a = (b == c)? d: e;
            >
            > Is just as understandable and more maintainable than
            >
            > if (b == c) {
            > a = d;
            > }
            > else {
            > a = e;
            > }[/color]

            It may be the only practical way to initialize a constant

            const int a = (b == c)? d: e;
            [color=blue]
            > In the first case it is obvious in one line that
            > you are simply assigning a value to a based on the condition.
            > The use of the if statement makes for a lot more code
            > that is subject to error in maintenance.
            >
            > Another issue that I have come across is the one way out of a function
            > issue. I contend that if there are conditions that warrant an earlier exit
            > from a function then the early exit should be taken. For eample:
            >
            > int funct(int arg)
            > {
            >
            > ....
            >
            > if (condition) return ERROR;
            >
            > ...
            >
            > return OK;
            >
            > is much better than
            >
            > int funct(int arg)
            > {
            > int retval = ERROR;
            > ....
            >
            > if (!condition) {
            > retval = OK;
            > (rest of function);
            > ...
            > } /* end of if ( !condition) */
            >
            > return retval;
            >[/color]

            This is a bit of a "straw man" argument.
            The problem is that functions which contain multiple exit points
            are extremely difficult to read, understand an maintain.
            Suppose, for example, that you need to modify the code
            and malloc some temporary storage.
            How do you ensure that that storage is free'd
            before any of the multiple exits?

            Maybe you can write more concise code
            with one, two, three or mre return statements.
            But where do you draw the line.
            The line has been drawn, perhaps somewhat arbitrarily,
            at a single point of return --
            preferrably at the end of the function.
            This simplifies cleanup, for example,
            because the thread of execution is guaranteed
            to run through any statements such as free
            which are placed just before it.
            [color=blue]
            > In the first case you've been very clear as to what values are going to be
            > returned, you've reduced the number of braces involved and you've reduced
            > the indentation level of the major part of the function. The argument
            > against this is that there may be some clean up that needs to be done in a
            > function and this style may lead an idiot to exit the function with out
            > doing the clean up. My rebuttal is that number one, only a small minority of
            > functions have the requirement that the clean up be done before exiting the
            > function. Number two, the clean up should be a separate function anyway that
            > can be called from anywhere in the parent function
            > and number three you just can't count on the standard
            > to protect the code from idiots anyway so why pretend that it does?
            >
            > A similar issue is this one:
            >
            > if (condition) {
            > retval = func(arg);
            > }
            >
            > If that condition has to be tested before each function,
            > then the condition should be evaluated by the function instead:
            >
            > retval = func(arg, condition);
            >
            > ...
            > int func(int arg, BOOLEAN condition)
            > {
            >
            > if (!condition) return OK;
            >
            > ...
            > }
            >
            > On the whole I consider less code to be more maintainable than lots of code.
            > Anywhere I can reduce the lines of code
            > then that makes it easier to maintain. For example:
            >
            > if(condition)
            > {
            > retval = func(a, b);
            > }
            > else
            > {
            > retval = func(a, c);
            > }
            >
            > if (retval != OK)
            > {
            > error_exit_func ();
            > }
            >
            > a much better way is
            >
            > if (!func(a, condition? b: c) error_exit_func ();
            >
            > Is there anybody out there who will agree with me on these issues
            > or am I the lone voice for this type of coding?[/color]

            As far a coding style is concerned
            that should be left up to each individual programmer.
            Any rules regarding the style used for code repositories
            can and should be resolved with a code reformatter such as indent



            From: E. Robert Tisdale
            Subject: Tisdale's C and C++ Style Guide
            Newsgroups: comp.lang.c, comp.lang.c++
            Date: 2003/01/13

            Style is a very subjective and personal consideration.
            C and C++ programmers develop or adopt a style
            in order to make their code easier for themselves
            and other programmers to read, understand and maintain.
            If you are developing your own style, there are no rules
            except that you should try to be consistent.
            Otherwise, you should try to adopt a style
            with which other C and C++ programmers are comfortable,
            familiar or that they will at least recognize.
            Personally, I try to use the same punctuation rules
            that are used for ordinary (mathematical) typesetting.
            Here are my recommendations :

            Terminators always follow immediately after an expression

            x@ for all @ in {?, :, ,, ;}

            and are followed by at least one white space.
            Write

            x? y: z

            instead of

            x ? y : z

            or

            x?y:z

            and write

            void f(int, int, int); void g(double);

            instead of

            void f(int,int,int); void g(double);

            for example.

            There is no space
            between some binary operators and their operands

            x@y for all @ in {::, ., ->, .*, ->*, *, /, %, &, ^, |}

            but there is always a space
            between other binary operators and their operands

            x @ y for all @ in {+, -, <<, >>;, <, <=, >, >=, ==, !=,
            &&, ||, =, *=, /=, %=, +=, -=, <<=, >>=, &=, |=, ^=}

            except when expressions appear as subscripts.
            Write

            x + y

            instead of

            x+y
            and

            x*y

            instead of

            x * y

            for example.
            But you may wish to write

            A[i+1][j-1]

            instead of

            A[i + 1][j - 1]

            for example to subscript array A.


            Most unary prefix operators never have any whitespace
            between themselves and their operands

            @x for all @ in {::, ++, --, ~, !, -, +, &, *}

            but others do

            @ x for all @ in {sizeof, new, delete, delete [], throw}

            No unary postfix operators

            x@ for all @ in {[], (), ++, --}

            ever have any whitespace between themselves and their operands.

            Use the normal typesetting rules for parentheses (),
            square brackets [], angle brackets <> and curly brackets {}.
            No space after (, [, < or { and no space before ), ], > or }.
            Write

            (x)

            instead of

            ( x )

            or

            (x )

            or

            ( x)

            and write

            [x]

            instead of

            [ x ]

            or

            [x ]

            or

            [ x]

            for example.
            There are, of course, exceptions
            where extra white space helps to make your code more readable:

            double A[2][3] = {{ 1, -1, 0},
            {-10, 11, -21}};


            Don't give identifiers cryptic, mangled names.
            Use ordinary, meaningful words, conventional symbols
            or abbreviations with annotations.
            Write

            double distance, velocity, acceleration, mass, Force;

            Force = mass*accelerati on;

            or

            double x; // distance
            double v; // velocity
            double a; // acceleration
            double m; // mass
            double F; // force

            F = m*a;

            for example.

            Don't rely on defaults. Make declarations explicit.
            Write

            int i = 1;

            instead of

            i = 1;

            to declare and initialize integer i and write

            class X {
            private:
            // Representation
            int I;
            public:
            // Constructors
            // ...
            };

            instead of

            class X {
            // Representation
            int I;
            public:
            // Constructors
            // ...
            };

            to define the private data members of class X for example.


            Use indentation to emphasize scope.
            Everybody is comfortable with standard indentation:

            void f(void)
            {
            // indent
            }

            But I indent curly brackets to the scope of the function body:

            void f(void)
            {
            // indent
            }

            And I include the open curly bracket with the function heading:

            void f(void) {
            // indent
            }

            to save a line of code.

            I always indent just two spaces at a time and
            I place just one statement on each line so that
            there is usually room for a comment at the end of each line
            beginning in column 33 or 41.

            Write

            if (condition) {
            // statements
            }

            instead of

            if(condition) {
            // statements
            }

            and

            while (condition) {
            // statements
            }

            instead of

            while(condition ) {
            // statements
            }

            to distinguish flow control structures from function calls.

            I use

            // comment

            for comments in C++ and I reserve

            /*
            a = b;
            // comment
            b = c;
            */

            to comment out code which may include comments.


            If you find yourself in an environment
            that requires you to conform to style rules with which you are not
            comfortable,
            consider investing a little time and effort in a program like astyle

            Artistic Style


            which changes the appearance of C or C++ programs
            by inserting or deleting whitespace.

            Write

            constant == variable

            instead of

            variable == constant

            when comparing a variable to a constant for equality
            so that if you write

            constant = variable

            by mistake, the compiler will detect the error.

            I always write

            x < y

            or

            x <= y

            instead of

            y > x

            or

            y >= x

            when comparing two values so that the expression is true
            when the left hand side is to the left of the right hand side
            on the real number line.

            Comment

            • Lawrence Kirby

              #7
              Re: Coding [style] standards

              On Sun, 19 Dec 2004 19:29:55 -0800, E. Robert Tisdale wrote:

              ....
              [color=blue][color=green]
              >> Another issue that I have come across is the one way out of a function
              >> issue. I contend that if there are conditions that warrant an earlier exit
              >> from a function then the early exit should be taken. For eample:
              >>
              >> int funct(int arg)
              >> {
              >>
              >> ....
              >>
              >> if (condition) return ERROR;
              >>
              >> ...
              >>
              >> return OK;
              >>
              >> is much better than
              >>
              >> int funct(int arg)
              >> {
              >> int retval = ERROR;
              >> ....
              >>
              >> if (!condition) {
              >> retval = OK;
              >> (rest of function);
              >> ...
              >> } /* end of if ( !condition) */
              >>
              >> return retval;
              >>[/color]
              >
              > This is a bit of a "straw man" argument.
              > The problem is that functions which contain multiple exit points
              > are extremely difficult to read, understand an maintain.[/color]

              They can also be very easy to read and maintain. The error is in trying to
              make this a style issue at all. Sometimes multiple returns are appropriate
              sometimes they aren't.
              [color=blue]
              > Suppose, for example, that you need to modify the code
              > and malloc some temporary storage.
              > How do you ensure that that storage is free'd
              > before any of the multiple exits?[/color]

              While this is a real issue there are many functions that are not affected
              by it.

              ....
              [color=blue]
              > Write
              >
              > constant == variable
              >
              > instead of
              >
              > variable == constant[/color]

              I have to say this is a pet hate of mine. You are significantly
              compromising the readability of the code for a limited case that many
              compilers will warn about anyway if you ask them to. IMO it is far better
              to write code that is more readable.
              [color=blue]
              > when comparing a variable to a constant for equality so that if you
              > write
              >
              > constant = variable
              >
              > by mistake, the compiler will detect the error.
              >
              > I always write
              >
              > x < y
              >
              > or
              >
              > x <= y
              >
              > instead of
              >
              > y > x
              >
              > or
              >
              > y >= x
              >
              > when comparing two values so that the expression is true when the left
              > hand side is to the left of the right hand side on the real number line.[/color]

              That doesn't always express the logic naturally, e.g.

              for (x = max; min <= x; x--)

              looks nasty to me. I'd have to flip the condition operation around in my
              minf to feel comfortable with what it is doing. Writing x >= min here is
              much more natural.

              Lawrence


              Comment

              • pete

                #8
                Re: Coding [style] standards

                Lawrence Kirby wrote:[color=blue]
                >
                > On Sun, 19 Dec 2004 19:29:55 -0800, E. Robert Tisdale wrote:[/color]
                [color=blue][color=green]
                > > Write
                > >
                > > constant == variable
                > >
                > > instead of
                > >
                > > variable == constant[/color]
                >
                > I have to say this is a pet hate of mine. You are significantly
                > compromising the readability of the code for a limited case that many
                > compilers will warn about anyway if you ask them to. IMO it is far
                > better to write code that is more readable.[/color]

                Is it really possible for someone who can understand
                variable == constant
                to get lost while trying to read
                constant == variable
                ?

                --
                pete

                Comment

                • pete

                  #9
                  Re: Coding standards

                  Natt Serrasalmus wrote:
                  [color=blue]
                  > a = (b == c) ? d : e;[/color]

                  You like those parentheses ?

                  --
                  pete

                  Comment

                  • CBFalconer

                    #10
                    Re: Coding [style] standards

                    Lawrence Kirby wrote:[color=blue]
                    >[/color]
                    .... snip ...[color=blue]
                    >
                    > looks nasty to me. I'd have to flip the condition operation around
                    > in my minf to feel comfortable with what it is doing. Writing
                    > x >= min here is much more natural.[/color]

                    Do you realize you are arguing with Trollsdale?

                    --
                    Chuck F (cbfalconer@yah oo.com) (cbfalconer@wor ldnet.att.net)
                    Available for consulting/temporary embedded and systems.
                    <http://cbfalconer.home .att.net> USE worldnet address!

                    Comment

                    • Thomas Stegen

                      #11
                      Re: Coding [style] standards

                      pete wrote:[color=blue]
                      >
                      > Is it really possible for someone who can understand
                      > variable == constant
                      > to get lost while trying to read
                      > constant == variable
                      > ?[/color]

                      No, but for me it break up the flow of reading. Not by much, but
                      breaking the flow for even less than a second is a problem and
                      increases the effort needed needlessly.

                      It does not need to be hard to read at all before it is to hard
                      to read. IOW, that something is only slightly harder to read is
                      a very strong argument against it.

                      --
                      Thomas.

                      Comment

                      • dandelion

                        #12
                        Re: Coding [style] standards


                        "Thomas Stegen" <thomas.stegen@ gmail.com> wrote in message
                        news:32o2i2F3o3 fpcU1@individua l.net...[color=blue]
                        > pete wrote:[color=green]
                        > >
                        > > Is it really possible for someone who can understand
                        > > variable == constant
                        > > to get lost while trying to read
                        > > constant == variable
                        > > ?[/color]
                        >
                        > No, but for me it break up the flow of reading.[/color]

                        Having made the same transition myself, I can attest it's a mere question of
                        getting used to it. The benefit of fishing out possibly unwanted assignments
                        outweighs the effort IMO.
                        [color=blue]
                        > It does not need to be hard to read at all before it is to hard
                        > to read. IOW, that something is only slightly harder to read is
                        > a very strong argument against it.[/color]

                        That's a good point, but can be solved with a little 'getting used to the
                        idea'.
                        However, I do not intend to embark on a private little style-war on this
                        subject.

                        "de gustibus non est disputandum" as the romans said.


                        Comment

                        • Chris Croughton

                          #13
                          Re: Coding [style] standards

                          On Mon, 20 Dec 2004 12:15:51 GMT, pete
                          <pfiland@mindsp ring.com> wrote:
                          [color=blue]
                          > Lawrence Kirby wrote:[color=green]
                          >>
                          >> On Sun, 19 Dec 2004 19:29:55 -0800, E. Robert Tisdale wrote:[/color]
                          >[color=green][color=darkred]
                          >> > Write
                          >> >
                          >> > constant == variable
                          >> >
                          >> > instead of
                          >> >
                          >> > variable == constant[/color]
                          >>
                          >> I have to say this is a pet hate of mine. You are significantly
                          >> compromising the readability of the code for a limited case that many
                          >> compilers will warn about anyway if you ask them to. IMO it is far
                          >> better to write code that is more readable.[/color]
                          >
                          > Is it really possible for someone who can understand
                          > variable == constant
                          > to get lost while trying to read
                          > constant == variable
                          > ?[/color]

                          Yes. Every time I see it (and I have cow orkers who do it a lot) I read
                          "1 == x" as "but 1 can never equal x, it's a constant". OK, it can be
                          understood eventually but it is non-obvious (in English I would never
                          say "if 10 is the number of cars", for instance) and delays finding
                          other errors. Since every compiler I have used in the last decade or so
                          will flag "if (x = 10)" as a potential error I find the "constant ==
                          variable" syntax unnecessarily confusing.

                          Chris C

                          Comment

                          • Chris Croughton

                            #14
                            Re: Coding standards

                            On Mon, 20 Dec 2004 12:17:36 GMT, pete
                            <pfiland@mindsp ring.com> wrote:
                            [color=blue]
                            > Natt Serrasalmus wrote:
                            >[color=green]
                            >> a = (b == c) ? d : e;[/color]
                            >
                            > You like those parentheses ?[/color]

                            My preference is to put the whole of the ternary expression within
                            parentheses, and additional parentheses for the condition only if it
                            ind/or the expressions are complex. So I'd write:

                            a = (b == c ? d : e);
                            a = ((b == c && d > e) ? (f + d*e) : (g + h*j));

                            I also put parentheses round expressions more complex than a simple
                            variable or constant (or sometime a simple function call) used in return
                            statements:

                            return 1;
                            return xyz;
                            return func(3);
                            return (a == b);
                            return (fred + bill*joe);

                            But that's my personal preferences, when working I conform to the local
                            style even when I dislike it...

                            Chris C

                            Comment

                            • Lawrence Kirby

                              #15
                              Re: Coding [style] standards

                              On Mon, 20 Dec 2004 12:30:54 +0000, CBFalconer wrote:
                              [color=blue]
                              > Lawrence Kirby wrote:[color=green]
                              >>[/color]
                              > ... snip ...[color=green]
                              >>
                              >> looks nasty to me. I'd have to flip the condition operation around
                              >> in my minf to feel comfortable with what it is doing. Writing
                              >> x >= min here is much more natural.[/color]
                              >
                              > Do you realize you are arguing with Trollsdale?[/color]

                              I know who I was replying to, yes. I try to base my responses on the merit
                              of the article rather than opinion about who posted it. While style issues
                              are always subjective I don't see any reason to dismiss the post I replied
                              to as so unreasonable as to ignore it. And of course if something looks
                              reasonable but is wrong (not a comment on this case) then it should not be
                              left unchallenged in the newsgroup.

                              Lawrence

                              Comment

                              Working...