Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #149567 > unrolled thread

Coding style for small if statements

Started byAnton Shepelev <anton.txt@gmail.com>
First post2020-01-31 23:46 +0300
Last post2020-02-29 03:30 -0800
Articles 20 on this page of 137 — 34 participants

Back to article view | Back to comp.lang.c


Contents

  Coding style for small if statements Anton Shepelev <anton.txt@gmail.com> - 2020-01-31 23:46 +0300
    Re: Coding style for small if statements Anton Shepelev <anton.txt@gmail.com> - 2020-01-31 23:54 +0300
      Re: Coding style for small if statements Les Cargill <lcargill99@comcast.com> - 2020-01-31 19:13 -0600
      Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-22 07:52 -0800
    Re: Coding style for small if statements Anton Shepelev <anton.txt@gmail.com> - 2020-02-01 00:06 +0300
      Re: Coding style for small if statements mathog <dmathog@gmail.com> - 2020-02-28 10:20 -0800
    Re: Coding style for small if statements Lew Pitcher <lew.pitcher@digitalfreehold.ca> - 2020-01-31 16:28 -0500
    Re: Coding style for small if statements donalhambra@gmail.com - 2020-02-01 04:55 -0800
      Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-01 17:16 +0000
        Re: Coding style for small if statements luser droog <luser.droog@gmail.com> - 2020-02-02 11:03 -0800
          Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-03 02:20 +0000
        Re: Coding style for small if statements Bonita Montero <Bonita.Montero@gmail.com> - 2020-02-03 05:17 +0100
          Re: Coding style for small if statements chad <cdalten@gmail.com> - 2020-02-03 04:07 -0800
            Re: Coding style for small if statements luser droog <luser.droog@gmail.com> - 2020-02-03 12:59 -0800
              Re: Coding style for small if statements chad <cdalten@gmail.com> - 2020-02-03 20:54 -0800
    Re: Coding style for small if statements nobody@example.org (Scott) - 2020-02-01 16:44 +0000
    Re: Coding style for small if statements already5chosen@yahoo.com - 2020-02-02 04:40 -0800
    Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-02 15:47 +0100
    Re: Coding style for small if statements Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-03 23:56 +0000
      Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-16 05:34 -0800
        Re: Coding style for small if statements Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-16 16:17 +0000
          Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-22 08:28 -0800
    Re: Coding style for small if statements skybuck2000@hotmail.com - 2020-02-03 21:52 -0800
      Re: Coding style for small if statements skybuck2000@hotmail.com - 2020-02-03 22:07 -0800
        Re: Coding style for small if statements skybuck2000@hotmail.com - 2020-02-03 22:22 -0800
          Re: Coding style for small if statements skybuck2000@hotmail.com - 2020-02-03 22:25 -0800
          Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-05 02:35 +0000
            Re: Coding style for small if statements James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-02-04 20:20 -0800
              Re: Coding style for small if statements James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-02-05 01:04 -0500
              Re: Coding style for small if statements James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-02-05 01:05 -0500
    Re: Coding style for small if statements John Bode <jfbode1029@gmail.com> - 2020-02-05 12:50 -0800
      Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-05 23:36 +0000
        Re: Coding style for small if statements John Bode <jfbode1029@gmail.com> - 2020-02-06 15:01 -0800
          Re: Coding style for small if statements Keith Thompson <Keith.S.Thompson+u@gmail.com> - 2020-02-06 15:43 -0800
            Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-07 11:02 +0100
              Re: Coding style for small if statements scott@slp53.sl.home (Scott Lurndal) - 2020-02-07 15:24 +0000
                Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-07 23:03 +0000
                  Re: Coding style for small if statements scott@slp53.sl.home (Scott Lurndal) - 2020-02-07 23:59 +0000
                    Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-08 00:16 +0000
                      Re: Coding style for small if statements scott@slp53.sl.home (Scott Lurndal) - 2020-02-08 02:26 +0000
            Re: Coding style for small if statements Les Cargill <lcargill99@comcast.com> - 2020-02-08 17:07 -0600
              Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-08 23:17 +0000
                Re: Coding style for small if statements Les Cargill <lcargill99@comcast.com> - 2020-02-08 18:32 -0600
                  Re: Coding style for small if statements Malcolm McLean <malcolm.arthur.mclean@gmail.com> - 2020-02-09 09:32 -0800
              Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-16 07:10 -0800
          Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-07 01:26 +0000
            Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-07 11:30 +0100
              Re: Coding style for small if statements chad <cdalten@gmail.com> - 2020-02-07 05:36 -0800
              Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-07 23:36 +0000
                Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-08 17:20 +0100
                  Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-09 02:07 +0000
                    Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-09 13:01 +0100
                      Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-09 13:26 +0000
                        Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-09 15:53 +0000
                        Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-09 17:03 +0100
                      Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-09 15:35 +0000
                        Re: Coding style for small if statements Manfred <noname@add.invalid> - 2020-02-09 18:07 +0100
                          Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-09 21:17 +0000
                          Pre- and post- conditions (was Re: Coding style for small if statements) Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-11 07:19 +0000
                            Re: Pre- and post- conditions (was Re: Coding style for small if statements) Öö Tiib <ootiib@hot.ee> - 2020-02-10 23:40 -0800
                              Re: Pre- and post- conditions (was Re: Coding style for small if statements) Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-12 12:24 +0000
                            Re: Pre- and post- conditions (was Re: Coding style for small if statements) Bart <bc@freeuk.com> - 2020-02-11 11:30 +0000
                            Re: Pre- and post- conditions (was Re: Coding style for small if statements) Joe Pfeiffer <pfeiffer@cs.nmsu.edu> - 2020-02-11 09:41 -0700
                            Re: Pre- and post- conditions (was Re: Coding style for small if statements) James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-02-12 08:12 -0500
                              Re: Pre- and post- conditions (was Re: Coding style for small if statements) Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-14 21:18 +0000
                              Re: Pre- and post- conditions (was Re: Coding style for small if statements) Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-22 00:01 -0800
                                Re: Pre- and post- conditions (was Re: Coding style for small if statements) James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-02-22 05:22 -0800
                                  Re: Pre- and post- conditions (was Re: Coding style for small if statements) Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-04-02 07:57 -0700
                                    Re: Pre- and post- conditions (was Re: Coding style for small if statements) James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-04-02 08:28 -0700
                            Re: Pre- and post- conditions (was Re: Coding style for small if statements) jadill33@gmail.com - 2020-02-12 07:56 -0800
                              Re: Pre- and post- conditions (was Re: Coding style for small if statements) chad <cdalten@gmail.com> - 2020-02-12 08:57 -0800
                            Re: Pre- and post- conditions (was Re: Coding style for small if statements) Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-14 21:31 +0000
                              Re: Pre- and post- conditions (was Re: Coding style for small if statements) jadill33@gmail.com - 2020-02-14 14:10 -0800
                                Re: Pre- and post- conditions (was Re: Coding style for small if statements) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-15 03:06 +0000
                        Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-09 19:45 +0100
                          Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-09 21:50 +0000
                            Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-09 22:51 +0000
                              Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-10 01:39 +0000
                                Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-10 09:55 +0100
                                  Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-10 11:07 +0000
                                    Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-10 12:48 +0100
                                      Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-10 13:13 +0000
                                        Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-10 15:15 +0100
                                      Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-10 15:46 +0000
                              Re: Coding style for small if statements James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-02-09 18:18 -0800
                            Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-10 09:12 +0100
                              Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-10 14:51 +0000
                                Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-10 16:19 +0000
                        Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-09 21:00 +0000
                          Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-09 21:29 +0000
                            Re: Coding style for small if statements luser droog <luser.droog@gmail.com> - 2020-02-09 17:14 -0800
                        Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-09 21:15 +0000
                          Re: Coding style for small if statements James Kuyper <jameskuyper@alumni.caltech.edu> - 2020-02-09 18:43 -0500
                            Re: Coding style for small if statements Ben Bacarisse <ben.usenet@bsb.me.uk> - 2020-02-10 01:25 +0000
                              Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-22 01:19 -0800
      Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-16 05:43 -0800
        Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-16 14:01 +0000
          Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-22 08:34 -0800
    Re: Coding style for small if statements Guillaume <message@bottle.org> - 2020-02-07 15:25 +0100
      Re: Coding style for small if statements Malcolm McLean <malcolm.arthur.mclean@gmail.com> - 2020-02-07 07:22 -0800
        Re: Coding style for small if statements Anton Shepelev <anton.txt@g{oogle}mail.com> - 2020-02-14 15:21 +0300
          Re: Coding style for small if statements Bart <bc@freeuk.com> - 2020-02-14 13:35 +0000
          Re: Coding style for small if statements Guillaume <message@bottle.org> - 2020-02-14 14:43 +0100
            Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-15 12:08 +0100
            Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-20 10:10 -0800
              Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-20 19:58 +0100
        Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-16 05:55 -0800
      Re: Coding style for small if statements scott@slp53.sl.home (Scott Lurndal) - 2020-02-07 15:26 +0000
        Re: Coding style for small if statements luser droog <luser.droog@gmail.com> - 2020-02-07 17:47 -0800
          Re: Coding style for small if statements jadill33@gmail.com - 2020-02-10 07:09 -0800
        Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-16 06:30 -0800
          Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-16 16:14 +0100
            Re: Coding style for small if statements Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-16 16:40 +0000
              Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-16 17:48 +0100
              Re: Coding style for small if statements Robert Wessel <robertwessel2@yahoo.com> - 2020-02-16 17:14 -0600
              Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-03-30 00:27 -0700
          Re: Coding style for small if statements Ike Naar <ike@sdf.lonestar.org> - 2020-02-16 18:39 +0000
            Re: Coding style for small if statements Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-16 20:37 +0000
              Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-02-17 09:09 +0100
                Re: Coding style for small if statements Öö Tiib <ootiib@hot.ee> - 2020-02-17 05:32 -0800
                Re: Coding style for small if statements scott@slp53.sl.home (Scott Lurndal) - 2020-02-17 18:07 +0000
                Re: Coding style for small if statements Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-02-17 23:48 +0000
                Re: Coding style for small if statements Richard Damon <Richard@Damon-Family.org> - 2020-02-17 20:40 -0500
            Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-23 10:14 -0800
              Re: Coding style for small if statements Ike Naar <ike@iceland.freeshell.org> - 2020-02-23 20:16 +0000
                Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-03-29 18:56 -0700
                  Re: Coding style for small if statements Ike Naar <ike@sdf.lonestar.org> - 2020-03-30 06:07 +0000
                    Re: Coding style for small if statements Jorgen Grahn <grahn+nntp@snipabacken.se> - 2020-03-30 06:45 +0000
                      Re: Coding style for small if statements David Brown <david.brown@hesbynett.no> - 2020-03-30 10:50 +0200
                        Re: Coding style for small if statements gazelle@shell.xmission.com (Kenny McCormack) - 2020-03-30 13:04 +0000
                          Re: Coding style for small if statements Malcolm McLean <malcolm.arthur.mclean@gmail.com> - 2020-03-30 06:17 -0700
                    Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-04-04 14:09 -0700
      Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-18 02:09 -0800
    Re: Coding style for small if statements Jens Stuckelberger <Jens_Stuckelberger@nowhere.net> - 2020-02-10 01:47 +0000
    Re: Coding style for small if statements Bonita Montero <Bonita.Montero@gmail.com> - 2020-02-12 17:54 +0100
    Re: Coding style for small if statements Tim Rentsch <tr.17687@z991.linuxsc.com> - 2020-02-20 07:18 -0800
    Re: Coding style for small if statements fir <profesor.fir@gmail.com> - 2020-02-29 03:30 -0800

Page 4 of 7 — ← Prev page 1 2 3 [4] 5 6 7  Next page →


#149966 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromJorgen Grahn <grahn+nntp@snipabacken.se>
Date2020-02-12 12:24 +0000
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<slrnr47rkc.km3.grahn+nntp@frailea.sa.invalid>
In reply to#149941
On Tue, 2020-02-11, Öö Tiib wrote:
> On Tuesday, 11 February 2020 09:19:54 UTC+2, Jorgen Grahn  wrote:
>> On Sun, 2020-02-09, Manfred wrote:
>> > On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
>> >> Of course, no one determines pre- and post-conditions these days and I
>> >> accept that that is now a lost art, 
>> 
>> > If it is of any relief, that's not my experience.
>> >
>> >> but in my very limited experience, I've found more bugs from simple
>> >> and informal reasoning about code than I ever found through
>> >> testing.
>> 
>> Me too. The only way I know to understand code is in terms of
>> preconditions and invariants.  I never write it down though and I
>> rarely speak about it.
>> 
>> I assume everyone else does this too, but I cannot be sure.
>> 
>> > On this side, I have found unit tests quite valuable instead,
>> > expecially when maintaining someone else's code.
>> 
>> The thing I have against unit tests is that, for me, writing tests
>> means I don't read the code as carefully.  If my tests pass, that
>> means the code is free of bugs, right?
>
> No, unit testing results with just somewhat less buggy programs with
> lower chance of breaking the logic with maintenance.

I should have been less flippant. I agree with what you write.
It's just that I find myself less motivated to "prove the code
correct" in my head if I also have unit tests.

In practice, I aim for a compromise, and use both tools.

/Jorgen

-- 
  // Jorgen Grahn <grahn@  Oo  o.   .     .
\X/     snipabacken.se>   O  o   .

[toc] | [prev] | [next] | [standalone]


#149942 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromBart <bc@freeuk.com>
Date2020-02-11 11:30 +0000
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<7fw0G.162815$co3.120684@fx11.am4>
In reply to#149940
On 11/02/2020 07:19, Jorgen Grahn wrote:
> On Sun, 2020-02-09, Manfred wrote:
>> On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
>>> Of course, no one determines pre- and post-conditions these days and I
>>> accept that that is now a lost art,
> 
>> If it is of any relief, that's not my experience.
>>
>>> but in my very limited experience, I've found more bugs from simple
>>> and informal reasoning about code than I ever found through
>>> testing.
> 
> Me too. The only way I know to understand code is in terms of
> preconditions and invariants.  I never write it down though and I
> rarely speak about it.
> 
> I assume everyone else does this too, but I cannot be sure.
> 
>> On this side, I have found unit tests quite valuable instead,
>> expecially when maintaining someone else's code.
> 
> The thing I have against unit tests is that, for me, writing tests
> means I don't read the code as carefully.  If my tests pass, that
> means the code is free of bugs, right?

Here's a fragment of code from a current project (say, a lexer, and 
expressed as C):


    enum {hstsize = 32768);           // ie. 2b1000_0000_0000_0000
    enum {hstmask = hstsize-1);       // ie. 2b0111_1111_1111_1111

    ...
    lookup(name, length, hashvalue & hstmask);
    ...
    lookup(name, length, hashvalue & hstmask);

Except that the last line (which wasn't called often, only for some 
language features) was mistakenly written as:

    lookup(name, length, hashvalue & hstsize);

It still worked fine, and would have passed all tests. It was just not 
quite as fast - compared with an older version that didn't have that bug 
- as I expected. The versions worked differently (the new one stored 
each new token, instead of yielding it to the parser) so it was just one 
of those things.

Yet, this bothered me enough to investigate further. With much larger 
inputs, larger than any realistic ones, the discrepancy was obvious 
(like, several times slower).

This is why I have no time for unit tests, since the real problems you 
encounter are never going to be detected. And they will not detect 
issues related to performance of quality of implementation, or even the 
quality of the code.

[toc] | [prev] | [next] | [standalone]


#149949 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromJoe Pfeiffer <pfeiffer@cs.nmsu.edu>
Date2020-02-11 09:41 -0700
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<1by2t9oz3r.fsf@pfeifferfamily.net>
In reply to#149940
Jorgen Grahn <grahn+nntp@snipabacken.se> writes:

> On Sun, 2020-02-09, Manfred wrote:
>> On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
>>> Of course, no one determines pre- and post-conditions these days and I
>>> accept that that is now a lost art, 
>
>> If it is of any relief, that's not my experience.
>>
>>> but in my very limited experience, I've found more bugs from simple
>>> and informal reasoning about code than I ever found through
>>> testing.
>
> Me too. The only way I know to understand code is in terms of
> preconditions and invariants.  I never write it down though and I
> rarely speak about it.
>
> I assume everyone else does this too, but I cannot be sure.

Having taught programming... the number of upper division undergrads who
will respond to "if you were to print the value of foo here, what would
it be?" with a completely blank look is both astonishing and depressing.

[toc] | [prev] | [next] | [standalone]


#149972 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromJames Kuyper <jameskuyper@alumni.caltech.edu>
Date2020-02-12 08:12 -0500
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<r20tk8$pt0$1@dont-email.me>
In reply to#149940
On 2/11/20 2:19 AM, Jorgen Grahn wrote:
...
> The thing I have against unit tests is that, for me, writing tests
> means I don't read the code as carefully. ...

That makes just as much sense, for exactly the same reason, as "I don't
like washing my hands because it means that I don't feel a need to avoid
people who are coughing and sneezing, and then I end up catching their
colds."

> ...If my tests pass, that
> means the code is free of bugs, right?

You are joking, right?

[toc] | [prev] | [next] | [standalone]


#150026 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromJorgen Grahn <grahn+nntp@snipabacken.se>
Date2020-02-14 21:18 +0000
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<slrnr4e3ks.km3.grahn+nntp@frailea.sa.invalid>
In reply to#149972
On Wed, 2020-02-12, James Kuyper wrote:
> On 2/11/20 2:19 AM, Jorgen Grahn wrote:
...
>> ...If my tests pass, that means the code is free of bugs, right?
>
> You are joking, right?

Yes; apologies (again) for not being more clear about that.

It was really a kind of reaction to the guy upthread who seemed to
recommend unit tests instead of reading and understanding the code.

/Jorgen

-- 
  // Jorgen Grahn <grahn@  Oo  o.   .     .
\X/     snipabacken.se>   O  o   .

[toc] | [prev] | [next] | [standalone]


#150139 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromTim Rentsch <tr.17687@z991.linuxsc.com>
Date2020-02-22 00:01 -0800
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<86zhdbcaoo.fsf@linuxsc.com>
In reply to#149972
James Kuyper <jameskuyper@alumni.caltech.edu> writes:

> On 2/11/20 2:19 AM, Jorgen Grahn wrote:
> ...
>
>> The thing I have against unit tests is that, for me, writing tests
>> means I don't read the code as carefully. ...
>
> That makes just as much sense, for exactly the same reason, as "I don't
> like washing my hands because it means that I don't feel a need to avoid
> people who are coughing and sneezing, and then I end up catching their
> colds."

Whether the original statement is true or not, the analogy
is flawed.

[toc] | [prev] | [next] | [standalone]


#150143 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromJames Kuyper <jameskuyper@alumni.caltech.edu>
Date2020-02-22 05:22 -0800
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<3e4ee590-e882-4442-9b5c-e8a07ff16dd8@googlegroups.com>
In reply to#150139
On Saturday, February 22, 2020 at 3:01:53 AM UTC-5, Tim Rentsch wrote:
> James Kuyper <jameskuyper@alumni.caltech.edu> writes:
> 
> > On 2/11/20 2:19 AM, Jorgen Grahn wrote:
> > ...
> >
> >> The thing I have against unit tests is that, for me, writing tests
> >> means I don't read the code as carefully. ...
> >
> > That makes just as much sense, for exactly the same reason, as "I don't
> > like washing my hands because it means that I don't feel a need to avoid
> > people who are coughing and sneezing, and then I end up catching their
> > colds."
> 
> Whether the original statement is true or not, the analogy
> is flawed.

Of course you feel that way - I don't think you've ever seen an analogy
that you liked. That's not a particularly useful response. A useful
response would identify the flaw, not merely claim that it exists. To
help you identify the flaw, here's the analogy, laid out in full:

1. There's a possible problem that you want to mitigate (delivering
defective code/catching a cold).

2. There's many different measures you can take to mitigate that
problem, two of which are A(unit tests/washing my hands regularly) and
B(reading the code carefully/avoiding contact with people displaying
cold symptoms).

3. The measures are at least somewhat independent, in the sense that
taking both measures will do a significantly better job of mitigating
the problem than using either method alone.

4. The argument is "I don't like taking measure A because doing so
encourages me to be lax about taking measure B".

5. The argument is defective in both cases, because in both cases the
best solution would be to take both measure A and measure B, without
skimping on either one. If you're not willing to do so, that's a
problem with you, not a problem with either remedy.

Would you please identify by number which of those descriptions doesn't
apply well to one or the other of the two problems? Also, please
identify which problem(s) you don't think it applies to, and provide an
explanation of why you feel that way. Please don't bother responding if
you're not willing to provide that explanation - such a response would
be just as useless as the one I'm responding to.

[toc] | [prev] | [next] | [standalone]


#150954 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromTim Rentsch <tr.17687@z991.linuxsc.com>
Date2020-04-02 07:57 -0700
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<861rp66il3.fsf@linuxsc.com>
In reply to#150143
James Kuyper <jameskuyper@alumni.caltech.edu> writes:

> On Saturday, February 22, 2020 at 3:01:53 AM UTC-5, Tim Rentsch wrote:
>
>> James Kuyper <jameskuyper@alumni.caltech.edu> writes:
>>
>>> On 2/11/20 2:19 AM, Jorgen Grahn wrote:
>>> ...
>>>
>>>> The thing I have against unit tests is that, for me, writing tests
>>>> means I don't read the code as carefully. ...
>>>
>>> That makes just as much sense, for exactly the same reason, as "I don't
>>> like washing my hands because it means that I don't feel a need to avoid
>>> people who are coughing and sneezing, and then I end up catching their
>>> colds."
>>
>> Whether the original statement is true or not, the analogy
>> is flawed.
>
> Of course you feel that way - I don't think you've ever seen an analogy
> that you liked.  That's not a particularly useful response. [...]

It's not my job to educate you.  As a rule I'm not inclined
to try to be helpful to people who seem to go out of their
way to make it difficult to provide help.

[toc] | [prev] | [next] | [standalone]


#150958 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromJames Kuyper <jameskuyper@alumni.caltech.edu>
Date2020-04-02 08:28 -0700
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<0d048e9e-a5a6-4fee-9897-6cb8258f60ba@googlegroups.com>
In reply to#150954
On Thursday, April 2, 2020 at 10:57:53 AM UTC-4, Tim Rentsch wrote:
> James Kuyper <jameskuyper@alumni.caltech.edu> writes:
> 
> > On Saturday, February 22, 2020 at 3:01:53 AM UTC-5, Tim Rentsch wrote:
...
> >> Whether the original statement is true or not, the analogy
> >> is flawed.
> >
> > Of course you feel that way - I don't think you've ever seen an analogy
> > that you liked.  That's not a particularly useful response. [...]
> 
> It's not my job to educate you.  As a rule I'm not inclined
> to try to be helpful to people who seem to go out of their
> way to make it difficult to provide help.

I have to agree that you have no obligation to properly explain your
comments - but you also have no obligation to say anything that makes
any sense whatsoever. Your habit of saying things without providing
needed explanation isn't much more useful than that.

[toc] | [prev] | [next] | [standalone]


#149976 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

Fromjadill33@gmail.com
Date2020-02-12 07:56 -0800
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<2c3ef28a-0935-462e-bac3-7ad4d973fd11@googlegroups.com>
In reply to#149940
On Tuesday, February 11, 2020 at 2:19:54 AM UTC-5, Jorgen Grahn wrote:
> On Sun, 2020-02-09, Manfred wrote:
> > On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
> >> Of course, no one determines pre- and post-conditions these days and I
> >> accept that that is now a lost art, 
> 
> > If it is of any relief, that's not my experience.
> >
> >> but in my very limited experience, I've found more bugs from simple
> >> and informal reasoning about code than I ever found through
> >> testing.
> 
> Me too. The only way I know to understand code is in terms of
> preconditions and invariants.  I never write it down though and I
> rarely speak about it.
> 
> I assume everyone else does this too, but I cannot be sure.

I make extensive use of pre-conditions validation in the code I write and
I feel they are invaluable for both early detection of issues and
documenting assumptions, especially during the development phase.

I basically use a modified version of the glib return macros, just modified
with function pointers underneath the hood to be able to customize the
report and response of what to do when one fails uniformly across a module
or project.  That way, I'm able to calibrate the reporting to either dump
to screen or log to some location, or calibrate the response by aborting
vs letting it go through.

Here is a small-ish code sample of how I use them.

\code
struct c_greg_date c_date_from_ordinal_day( c_greg_year year,
                                            c_greg_day_of_year day )
{
  struct c_greg_date date;
  int days_in_month;

  c_return_value_if_fail( year >= C_GREGORIAN_EPOCH_YEAR, gc_invalid_greg_date );
  c_return_value_if_fail( day >= 1 && day <= c_days_in_year( year ), gc_invalid_greg_date );

  date.year = year;

  date.month = C_JANUARY;
  days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
  while ( day > days_in_month )
  {
    day -= days_in_month;
    date.month++;

    days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
  }
  date.day = day;

  return date;
}

struct c_greg_date c_date_from_iso_week( struct c_iso_week_date iso_wk_date )
{
  struct c_greg_date date;
  c_day_duration days;

  c_return_value_if_fail( c_is_valid_iso_week( iso_wk_date ), gc_invalid_greg_date );

  /*
   * Calculating the gregorian date from an ISO week date is rather
   * simple provided that one can find the corresponding Gregorian
   * date for the first Monday of week 1 for the given year.
   */

  days = (iso_wk_date.week - 1) * C_DAYS_IN_WEEK;
  days += iso_wk_date.day - C_ISO_MONDAY;
  date = c_date_add_days( c_date_first_day_of_iso8601_week_one( iso_wk_date.year ), days );

  return date;
}

struct c_greg_date c_date_from_day_number( date_t days )
{
  struct c_greg_date date;
  int year = C_GREGORIAN_EPOCH_YEAR;
  int days_in_month;

  c_return_value_if_fail( days >= 0, gc_invalid_greg_date );

  while ( days >= C_DAYS_IN_GREGORIAN_CYCLE )
  {
    days -= C_DAYS_IN_GREGORIAN_CYCLE;
    year += C_YEARS_IN_GREGORIAN_CYCLE;
  }

  while ( days >= c_days_in_year( year ) )
  {
    days -= c_days_in_year( year );
    year++;
  }
  date.year = year;

  date.month = C_JANUARY;
  days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
  while ( days >= days_in_month )
  {
    days -= days_in_month;
    date.month++;

    days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
  }
  date.day = days + 1;

  return date;
}
\endcode

Invariants are a logical step forward once you have a framework to handle
preconditions.

\endcode
#define C_ARRAY_INVARIANT( carray )                                         \
  do                                                                        \
  {                                                                         \
    C_INVARIANT( (carray)->buffer != NULL );                                \
    C_INVARIANT( (carray)->size <= (carray)->alloc_size );                  \
    C_INVARIANT( (carray)->is_pointer ? true : (carray)->free_fn == NULL ); \
  } while (0)

void gc_array_push_back_n( struct c_array* array,
                           void* objects,
                           size_t n,
                           size_t type_sz )
{
  size_t a_memory;
  size_t n_memory;
  size_t subarray_offset;
  bool expand_valid;

  c_return_if_fail( array != NULL );
  c_return_if_fail( objects != NULL );
  c_return_if_fail( array->element_size == type_sz );
  C_ARRAY_INVARIANT( array );

  /*
   * It is possible that the object pointer will reference an object
   * within the array itself.  If object is a member of the array,
   * and the new object will overflow the array buffer, then the
   * object pointer will be invalidated when the old array is copied
   * into a new larger buffer.  To remedy this issue, an offset is
   * needed to reference the object pointer relative to the start of
   * the array buffer.  Then, when the array buffer is resized, the
   * object pointer can be relocated to the new buffer using that
   * offset in the new array buffer.
   *
   * The C standard makes no guarantees about the underlying storage
   * of the array buffer.  Most architectures store them in a
   * contiguous section of memory, but understand that the C standard
   * does not guarantee it.  The determination of whether the object
   * pointer is a member of the array assumes that the buffer memory
   * address space is contiguous.  However, this assumption should
   * be valid for the majority of modern computer architectures.
   */
  a_memory = array->alloc_size * array->element_size;

  if ( objects >= array->buffer &&
       (unsigned char*)objects <= (unsigned char*)array->buffer + a_memory )
  {
    /* Record the offset of the object pointer. */
    subarray_offset = (unsigned char*)objects - (unsigned char*)array->buffer;

    expand_valid = gc_array_maybe_expand( array, n );

    /* Restore the object pointer using the offset in the possibly
       new array buffer. */
    objects = (unsigned char*)array->buffer + subarray_offset;
  }
  else {
    expand_valid = gc_array_maybe_expand( array, n );
  }

  if ( expand_valid )
  {
    a_memory = array->size * array->element_size;
    n_memory = n * array->element_size;
    memcpy( (unsigned char*)array->buffer + a_memory, objects, n_memory );
    array->size += n;
  }
  else {
    c_unexpected( "gc_array_maybe_expand failed" );
  }

  C_ARRAY_INVARIANT( array );
}
\endcode

If you provide robust precondition and invariants to your interfaces,
you can increase flexibility to the user by not requiring opaque pointers
to your structures, but rest on the fact that if the user munges something
up in a structure and passes it to your API, you can detect that and report
that bad data early.

The hard part for me is trying to have the granularity to turn precondition
or invariant evaluation (which has a run time cost), which introduces more
complexity into the build system and code source tree.  For example, I
may have a precondition that verifies an array is sorted before in do a
binary search, but for large arrays, the cost of that can prohibitive.

In my limited experience, any kind of structured precondition checking
you add to code has been well worth the cost.  The main hurdle is getting
consensus on a methodology to unify their implementation to take a lot of
the repetitiveness out.  And for me that was adapting the glib return
macros.

> > On this side, I have found unit tests quite valuable instead,
> > expecially when maintaining someone else's code.
> 
> The thing I have against unit tests is that, for me, writing tests
> means I don't read the code as carefully.  If my tests pass, that
> means the code is free of bugs, right?

I feel like I've always struggled with unit testing not for reading the
code as carefully, but because they are harder and more work than
using preconditions and invariants, and I've never been in a place where
unit testing was done (I haven't worked in a lot of environments).

I struggle with the idea of development using unit testing because it's
a lot of work to provide coverage of code with the myriad of corner
cases you can find yourself in, and if you have requirements drift, the
more complete your unit tests are, the more effort it takes to revamp them.
There seems to be some people where that the development style clicks for
them.  That combined with my lack of skill with unit tests reinforces my
work ethic to avoid them until the project is winding down.

So if I do end up writing unit tests, it's to provide a modicum of security
that someone else doesn't make a single line change that blows up a large
majority of the tests (it happens!), but typically it's after the project
is largely implemented.  Time is commonly the reason why unit testing goes
undone for me.  This is because preconditions are relatively quick to add,
but comprehensive unit testing I've found to be quite labor intensive.  Unit
tests are awesome when the module is stable and most of the code changes are
largely for maintenance or "performance improvement" reasons.

Best regards,
John D.

[toc] | [prev] | [next] | [standalone]


#149978 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

Fromchad <cdalten@gmail.com>
Date2020-02-12 08:57 -0800
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<f705d1cb-4e3f-4afd-8fbd-f55912b35f90@googlegroups.com>
In reply to#149976
On Wednesday, February 12, 2020 at 7:56:33 AM UTC-8, jadi...@gmail.com wrote:
> On Tuesday, February 11, 2020 at 2:19:54 AM UTC-5, Jorgen Grahn wrote:
> > On Sun, 2020-02-09, Manfred wrote:
> > > On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
> > >> Of course, no one determines pre- and post-conditions these days and I
> > >> accept that that is now a lost art, 
> > 
> > > If it is of any relief, that's not my experience.
> > >
> > >> but in my very limited experience, I've found more bugs from simple
> > >> and informal reasoning about code than I ever found through
> > >> testing.
> > 
> > Me too. The only way I know to understand code is in terms of
> > preconditions and invariants.  I never write it down though and I
> > rarely speak about it.
> > 
> > I assume everyone else does this too, but I cannot be sure.
> 
> I make extensive use of pre-conditions validation in the code I write and
> I feel they are invaluable for both early detection of issues and
> documenting assumptions, especially during the development phase.
> 
> I basically use a modified version of the glib return macros, just modified
> with function pointers underneath the hood to be able to customize the
> report and response of what to do when one fails uniformly across a module
> or project.  That way, I'm able to calibrate the reporting to either dump
> to screen or log to some location, or calibrate the response by aborting
> vs letting it go through.
> 
> Here is a small-ish code sample of how I use them.
> 
> \code
> struct c_greg_date c_date_from_ordinal_day( c_greg_year year,
>                                             c_greg_day_of_year day )
> {
>   struct c_greg_date date;
>   int days_in_month;
> 
>   c_return_value_if_fail( year >= C_GREGORIAN_EPOCH_YEAR, gc_invalid_greg_date );
>   c_return_value_if_fail( day >= 1 && day <= c_days_in_year( year ), gc_invalid_greg_date );
> 
>   date.year = year;
> 
>   date.month = C_JANUARY;
>   days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
>   while ( day > days_in_month )
>   {
>     day -= days_in_month;
>     date.month++;
> 
>     days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
>   }
>   date.day = day;
> 
>   return date;
> }
> 
> struct c_greg_date c_date_from_iso_week( struct c_iso_week_date iso_wk_date )
> {
>   struct c_greg_date date;
>   c_day_duration days;
> 
>   c_return_value_if_fail( c_is_valid_iso_week( iso_wk_date ), gc_invalid_greg_date );
> 
>   /*
>    * Calculating the gregorian date from an ISO week date is rather
>    * simple provided that one can find the corresponding Gregorian
>    * date for the first Monday of week 1 for the given year.
>    */
> 
>   days = (iso_wk_date.week - 1) * C_DAYS_IN_WEEK;
>   days += iso_wk_date.day - C_ISO_MONDAY;
>   date = c_date_add_days( c_date_first_day_of_iso8601_week_one( iso_wk_date.year ), days );
> 
>   return date;
> }
> 
> struct c_greg_date c_date_from_day_number( date_t days )
> {
>   struct c_greg_date date;
>   int year = C_GREGORIAN_EPOCH_YEAR;
>   int days_in_month;
> 
>   c_return_value_if_fail( days >= 0, gc_invalid_greg_date );
> 
>   while ( days >= C_DAYS_IN_GREGORIAN_CYCLE )
>   {
>     days -= C_DAYS_IN_GREGORIAN_CYCLE;
>     year += C_YEARS_IN_GREGORIAN_CYCLE;
>   }
> 
>   while ( days >= c_days_in_year( year ) )
>   {
>     days -= c_days_in_year( year );
>     year++;
>   }
>   date.year = year;
> 
>   date.month = C_JANUARY;
>   days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
>   while ( days >= days_in_month )
>   {
>     days -= days_in_month;
>     date.month++;
> 
>     days_in_month = gc_days_in_month_table[LEAP_INDEX(year)][date.month - 1];
>   }
>   date.day = days + 1;
> 
>   return date;
> }
> \endcode
> 
> Invariants are a logical step forward once you have a framework to handle
> preconditions.
> 
> \endcode
> #define C_ARRAY_INVARIANT( carray )                                         \
>   do                                                                        \
>   {                                                                         \
>     C_INVARIANT( (carray)->buffer != NULL );                                \
>     C_INVARIANT( (carray)->size <= (carray)->alloc_size );                  \
>     C_INVARIANT( (carray)->is_pointer ? true : (carray)->free_fn == NULL ); \
>   } while (0)
> 
> void gc_array_push_back_n( struct c_array* array,
>                            void* objects,
>                            size_t n,
>                            size_t type_sz )
> {
>   size_t a_memory;
>   size_t n_memory;
>   size_t subarray_offset;
>   bool expand_valid;
> 
>   c_return_if_fail( array != NULL );
>   c_return_if_fail( objects != NULL );
>   c_return_if_fail( array->element_size == type_sz );
>   C_ARRAY_INVARIANT( array );
> 
>   /*
>    * It is possible that the object pointer will reference an object
>    * within the array itself.  If object is a member of the array,
>    * and the new object will overflow the array buffer, then the
>    * object pointer will be invalidated when the old array is copied
>    * into a new larger buffer.  To remedy this issue, an offset is
>    * needed to reference the object pointer relative to the start of
>    * the array buffer.  Then, when the array buffer is resized, the
>    * object pointer can be relocated to the new buffer using that
>    * offset in the new array buffer.
>    *
>    * The C standard makes no guarantees about the underlying storage
>    * of the array buffer.  Most architectures store them in a
>    * contiguous section of memory, but understand that the C standard
>    * does not guarantee it.  The determination of whether the object
>    * pointer is a member of the array assumes that the buffer memory
>    * address space is contiguous.  However, this assumption should
>    * be valid for the majority of modern computer architectures.
>    */
>   a_memory = array->alloc_size * array->element_size;
> 
>   if ( objects >= array->buffer &&
>        (unsigned char*)objects <= (unsigned char*)array->buffer + a_memory )
>   {
>     /* Record the offset of the object pointer. */
>     subarray_offset = (unsigned char*)objects - (unsigned char*)array->buffer;
> 
>     expand_valid = gc_array_maybe_expand( array, n );
> 
>     /* Restore the object pointer using the offset in the possibly
>        new array buffer. */
>     objects = (unsigned char*)array->buffer + subarray_offset;
>   }
>   else {
>     expand_valid = gc_array_maybe_expand( array, n );
>   }
> 
>   if ( expand_valid )
>   {
>     a_memory = array->size * array->element_size;
>     n_memory = n * array->element_size;
>     memcpy( (unsigned char*)array->buffer + a_memory, objects, n_memory );
>     array->size += n;
>   }
>   else {
>     c_unexpected( "gc_array_maybe_expand failed" );
>   }
> 
>   C_ARRAY_INVARIANT( array );
> }
> \endcode
> 
> If you provide robust precondition and invariants to your interfaces,
> you can increase flexibility to the user by not requiring opaque pointers
> to your structures, but rest on the fact that if the user munges something
> up in a structure and passes it to your API, you can detect that and report
> that bad data early.
> 
> The hard part for me is trying to have the granularity to turn precondition
> or invariant evaluation (which has a run time cost), which introduces more
> complexity into the build system and code source tree.  For example, I
> may have a precondition that verifies an array is sorted before in do a
> binary search, but for large arrays, the cost of that can prohibitive.
> 
> In my limited experience, any kind of structured precondition checking
> you add to code has been well worth the cost.  The main hurdle is getting
> consensus on a methodology to unify their implementation to take a lot of
> the repetitiveness out.  And for me that was adapting the glib return
> macros.
> 
> > > On this side, I have found unit tests quite valuable instead,
> > > expecially when maintaining someone else's code.
> > 
> > The thing I have against unit tests is that, for me, writing tests
> > means I don't read the code as carefully.  If my tests pass, that
> > means the code is free of bugs, right?
> 
> I feel like I've always struggled with unit testing not for reading the
> code as carefully, but because they are harder and more work than
> using preconditions and invariants, and I've never been in a place where
> unit testing was done (I haven't worked in a lot of environments).
> 
> I struggle with the idea of development using unit testing because it's
> a lot of work to provide coverage of code with the myriad of corner
> cases you can find yourself in, and if you have requirements drift, the
> more complete your unit tests are, the more effort it takes to revamp them.
> There seems to be some people where that the development style clicks for
> them.  That combined with my lack of skill with unit tests reinforces my
> work ethic to avoid them until the project is winding down.
> 
> So if I do end up writing unit tests, it's to provide a modicum of security
> that someone else doesn't make a single line change that blows up a large
> majority of the tests (it happens!), but typically it's after the project
> is largely implemented.  Time is commonly the reason why unit testing goes
> undone for me.  This is because preconditions are relatively quick to add,
> but comprehensive unit testing I've found to be quite labor intensive.  Unit
> tests are awesome when the module is stable and most of the code changes are
> largely for maintenance or "performance improvement" reasons.
> 

So like the chick next to me at the LinkedIn Corporate office shared open space is actually a dude.

[toc] | [prev] | [next] | [standalone]


#150027 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromJorgen Grahn <grahn+nntp@snipabacken.se>
Date2020-02-14 21:31 +0000
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<slrnr4e4co.km3.grahn+nntp@frailea.sa.invalid>
In reply to#149940
On Tue, 2020-02-11, Jorgen Grahn wrote:
> On Sun, 2020-02-09, Manfred wrote:
>> On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
>>> Of course, no one determines pre- and post-conditions these days and I
>>> accept that that is now a lost art, 
>
>> If it is of any relief, that's not my experience.
>>
>>> but in my very limited experience, I've found more bugs from simple
>>> and informal reasoning about code than I ever found through
>>> testing.
>
> Me too. The only way I know to understand code is in terms of
> preconditions and invariants.  I never write it down though and I
> rarely speak about it.
>
> I assume everyone else does this too, but I cannot be sure.

I asked some of my younger coworkers.  They were only vaguely familiar
with the terms "precondition", "postcondition" and "invariant".  One
guy remembered them vaguely from the C++ Core Guidelines[0].  Another
(who's an excellent troubleshooter) agreed maybe he thinks in terms of
which conditions hold where.

Then we had to get back to work, so it's still unclear to me if it's a
lost art or not.

/Jorgen

[0] http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-pre

-- 
  // Jorgen Grahn <grahn@  Oo  o.   .     .
\X/     snipabacken.se>   O  o   .

[toc] | [prev] | [next] | [standalone]


#150028 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

Fromjadill33@gmail.com
Date2020-02-14 14:10 -0800
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<717d8844-50ee-4efa-afe7-dd6d475e0bca@googlegroups.com>
In reply to#150027
On Friday, February 14, 2020 at 4:31:13 PM UTC-5, Jorgen Grahn wrote:
> On Tue, 2020-02-11, Jorgen Grahn wrote:
> > On Sun, 2020-02-09, Manfred wrote:
> >> On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
> >>> Of course, no one determines pre- and post-conditions these days and I
> >>> accept that that is now a lost art, 
> >
> >> If it is of any relief, that's not my experience.
> >>
> >>> but in my very limited experience, I've found more bugs from simple
> >>> and informal reasoning about code than I ever found through
> >>> testing.
> >
> > Me too. The only way I know to understand code is in terms of
> > preconditions and invariants.  I never write it down though and I
> > rarely speak about it.
> >
> > I assume everyone else does this too, but I cannot be sure.
> 
> I asked some of my younger coworkers.  They were only vaguely familiar
> with the terms "precondition", "postcondition" and "invariant".  One
> guy remembered them vaguely from the C++ Core Guidelines[0].  Another
> (who's an excellent troubleshooter) agreed maybe he thinks in terms of
> which conditions hold where.
> 
> Then we had to get back to work, so it's still unclear to me if it's a
> lost art or not.

The problem with design by contract is that there isn't great support
for it for the C language.  I've played with it a little myself.  You can
sort of mimic it with some macro help.  I tend to program to the earliest
C standard, so there's scoping issues that muddy the implementation.

Here's one methodology of how I've tried it out.  When contract evaluation
is enabled by the build system, those design by contract statements are
turned on, and any issues reported.  It's not pretty, but I think don't
think it's a useless idea.  Ideally, you should be able to package the
C_POST statements (that are evaluated when postcondition is turned on)
into the ENSURE block to isolate the postcondition from the implementation,
but I haven't figured out a way in C to do that.

\code
#include <stdio.h>
#include <clover/macros.h>
#include <clover/contract.h>

const double tolerance = 0.0000001;
const int max_iterations = 5;

double heron_sqrt( double x );
double heron_sqrt_impl( double x );

int main( void )
{
  size_t idx;
  char tmp_str[40];

  double input[] = {
    0, 1, 10, 100, 1000, 10000, 0.1, 0.25, -1
  };

  for ( idx = 0; idx < c_sizeof_array (input); ++idx )
  {
    snprintf( tmp_str, sizeof (tmp_str), "sqrt( %.2f )", input[idx] );
    printf( "%-20s = %.10f\n", tmp_str, heron_sqrt( input[idx] ) );
  }

  return 0;
}

double heron_sqrt( double x )
{
  double sqrt_x = 0;
  C_POST( double x_sq; )

  C_REQUIRE( x >= 0 && "sqrt argument should be non-negative" );

  sqrt_x = heron_sqrt_impl( x );

  C_POST( x_sq = sqrt_x * sqrt_x; )
  C_ENSURE( ( x_sq - tolerance <= x && x <= x_sq + tolerance ) &&
            "sqrt result is out of tolerance" );

  return sqrt_x;
}

double heron_sqrt_impl( double x )
{
  /*
   * The algorithm used to calculate the square root 'x' of number 'S'
   * is based on Heron's method.
   *
   * Let x(0) be an arbitrary positive number.
   * Let x(n+1) be the average of x(n) and 'S / x(n)'
   * Repeat until the desired accuracy is achieved.
   *
   * The closer x(0) is to the square root value, the fewer number
   * of iterations are needed to converge to the accuracy required.
   *
   * The global variable 'max_iterations' allows the person to
   * limit the accuracy of the result to cause postcondition
   * violations.
   */ 

  double sqrt_x = 0;
  double guess = 0;
  double error = 0;
  int itr = 0;

  if ( x == 0.0 ) {
    sqrt_x = 0;
  }
  else
  {
    sqrt_x = x * 0.5;

    do
    {
      guess = sqrt_x;
      sqrt_x = 0.5 * ( guess + x / guess );
      error = sqrt_x * sqrt_x - x;
      error = error < 0 ? -error : error;
      ++itr;
    } while ( error > tolerance && itr < max_iterations );
  }

  return sqrt_x;
}
\endcode

Contract failures would show up like:

Precondition failed: x >= 0 && "sqrt argument should be non-negative", file c_contract_sqrt_example.c, line 34, function heron_sqrt

or

Postcondition failed: ( x_sq - tolerance <= x && x <= x_sq + tolerance ) && "sqrt result is out of tolerance", file c_contract_sqrt_example.c, line 39, function heron_sqrt

Best regards,
John D.

[toc] | [prev] | [next] | [standalone]


#150029 — Re: Pre- and post- conditions (was Re: Coding style for small if statements)

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2020-02-15 03:06 +0000
SubjectRe: Pre- and post- conditions (was Re: Coding style for small if statements)
Message-ID<87k14oft0z.fsf@bsb.me.uk>
In reply to#150028
jadill33@gmail.com writes:

> On Friday, February 14, 2020 at 4:31:13 PM UTC-5, Jorgen Grahn wrote:
>> On Tue, 2020-02-11, Jorgen Grahn wrote:
>> > On Sun, 2020-02-09, Manfred wrote:
>> >> On 2/9/2020 4:35 PM, Ben Bacarisse wrote:
>> >>> Of course, no one determines pre- and post-conditions these days and I
>> >>> accept that that is now a lost art, 
>> >
>> >> If it is of any relief, that's not my experience.
>> >>
>> >>> but in my very limited experience, I've found more bugs from simple
>> >>> and informal reasoning about code than I ever found through
>> >>> testing.
>> >
>> > Me too. The only way I know to understand code is in terms of
>> > preconditions and invariants.  I never write it down though and I
>> > rarely speak about it.
>> >
>> > I assume everyone else does this too, but I cannot be sure.
>> 
>> I asked some of my younger coworkers.  They were only vaguely familiar
>> with the terms "precondition", "postcondition" and "invariant".  One
>> guy remembered them vaguely from the C++ Core Guidelines[0].  Another
>> (who's an excellent troubleshooter) agreed maybe he thinks in terms of
>> which conditions hold where.
>> 
>> Then we had to get back to work, so it's still unclear to me if it's a
>> lost art or not.
>
> The problem with design by contract is that there isn't great support
> for it for the C language.

True.  A methodology like design by contract would benefit from good
support in your tools.

But, just to be clear for readers who might be getting confused, the
topic was not contracts but reasoning about code.

<cut example>
-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#149890

FromDavid Brown <david.brown@hesbynett.no>
Date2020-02-09 19:45 +0100
Message-ID<r1pk0q$j9i$1@dont-email.me>
In reply to#149883
On 09/02/2020 16:35, Ben Bacarisse wrote:
> David Brown <david.brown@hesbynett.no> writes:
> 
>> On 09/02/2020 03:07, Ben Bacarisse wrote:
>>> This exchange is, I feel, not very productive.  You seem to be
>>> attributing to me views I don't have and arguing against those.
>>>
>>> In particular, you seem to think I don't value "clarity" in code and,
>>> secondarily, that I think code is for computers not humans.  I don't
>>> know how you got that from what I wrote.  Maybe I was not clear.
>>>
>>> Anyway, I'm going to reply to only a couple of very specific points
>>> because I am not against writing clear code.
>>
>> I don't think you gave the impression of being against writing clear
>> code, and I am sorry if it looked as though I thought that.
>>
>> I think merely that we have different opinions as to what comprises
>> clear code, and perhaps different emphasis on the benefits of
>> particular details of code formatting choices.
>>
>> And while we both prefer to write clear code (for different measures
>> of "clear"), we may also have different levels of dislike of unclear
>> code.
>>
>>
>>>
>>> David Brown <david.brown@hesbynett.no> writes:
>>>
>>>> On 08/02/2020 00:36, Ben Bacarisse wrote:
>>>>> David Brown <david.brown@hesbynett.no> writes:
>>>>>
>>>>>> On 07/02/2020 02:26, Ben Bacarisse wrote:
>>>>>>> John Bode <jfbode1029@gmail.com> writes:
>>>>>>>
>>>>>>>> On Wednesday, February 5, 2020 at 5:36:14 PM UTC-6, Ben Bacarisse wrote:
>>>>>>>>> John Bode <jfbode1029@gmail.com> writes:
>>>>>>>>>
>> <snip>
>>>>>
>>>>
>>>> I know which "if" the "else" belonged to.  But I don't think the
>>>> format of the code matches the semantics of the code, and I think that
>>>> is bad style - it risks confusion.
>>>
>>> What is the confusion that is risked?  Do you mean thata there are at
>>> least two meanings that could be considered for the original code?  If
>>> so, what are those?  If not, what is the risk you see?
>>
>> Looking back at the original code (this thread has got a bit too
>> long), I don't think I would have trouble understanding the meaning.
>> But it requires more mental effort than it should do in order to read
>> the code. And the point of the original post is that some people might
>> well see two possible meanings of it.  Not all people reading C code
>> are as experienced as you or I.
> 
> This is where it gets so frustrating.  Who are these people who can give
> that code more than one totally obvious meaning, and why are they even
> reading C much less possibly maintaining it?  Have you ever met such a
> person?  Why were they reading C code?  If you have come across such a
> programmer, what is the other interpretation that they might consider?
> 

I have certainly met people who work (at least some of the time) as 
programmers, who have a terrible idea of how to code.  I have seen code 
written by people who really should not have been allowed in front of a 
keyboard.  I have seen code by people who view warnings about mismatches 
in the number of parameters in a function declaration and function usage 
as "merely a warning" and therefore not something to worry about.

> I really want to understand other people's perspectives on this because
> my imagination fails me here.  I think I have a syntax-oriented brain.
> Syntax errors (or formatting oddities like the one you show below) just
> SCREAM AT ME and I react in an almost visceral way to them.

I have the same reaction.  But I know there are plenty of programmers 
who don't.

I suspect that your challenge here is that you are a very good 
programmer.  Programming is a discipline in which there is a small 
proportion that are extraordinarily good - people who are an order of 
magnitude more productive than the median, or who can quickly and easily 
pick up new languages, read the rules of a language once and remember 
them, people who can't bring themselves to write formatting oddities and 
find it difficult to understand how anyone else could do so.  Most 
programmers are far from that level.  And a great many people who write 
code are complete amateurs - they have little or no education or 
training in it, and their main job and experience can be something 
completely different.

> 
>> Some of the later examples in the thread have had more scope for
>> confusion, where it is unclear whether the programmer meant one thing
>> and wrote semantically incorrect code, or meant to write what the C
>> code says, but did so with unclear formatting.
> 
> I'll just note that I am much less interested in the intent of the
> author than others seem to be.  Of course the code should be clear, and
> the formatting and layout should reflect the syntax (it can't really
> reflect the intent unless the code is also correct) but I don't read
> what I think the author meant, I read what the author wrote.

Fair enough - we have different thoughts here.  I am not happy with code 
until I am confident that I can see what the author meant, and that it 
clearly matches what the author wrote.

But perhaps the difference is in what we are talking about in regard to 
the code.  If you want to know what the code does, then the C meaning of 
the code is all that matters.  If you want to judge the quality of the 
code and see if the programmer's job is complete and the code is ready 
for deployment, delivery to the customer, etc., then the balance is 
different.

> 
>>> <cut>
>>>>>>> What's more, you are suggesting that code errors of this sort frequently
>>>>>>> survive long enough for someone like you to see them.  Whilst C programs
>>>>>>> can have subtle errors that go uncaught for some time, your people
>>>>>>> should have a testing regime in place so that basic errors of logic get
>>>>>>> caught immediately.
>>>>>>
>>>>>> Of course it is important to have good test regimes in place - noting
>>>>>> again that everyone involved is human and tests are never perfect.  In
>>>>>> particular, testing can never prove the absence of bugs, but only prove
>>>>>> their presence.
>>>>>
>>>>> But in the case in point there is a bug!  People do write silly things
>>>>> like putting code next to branch of an if whilst forgetting to add the
>>>>> {}s.  But the result is code with a bug that will be found in the very
>>>>> first test run.  This is either a non-issue (as I hope it would be in
>>>>> most production environments), or it signals that something else is
>>>>> seriously wrong.
>>>>
>>>> How many programs are written with /complete/ test coverage?  I expect
>>>> that if you round to the nearest tenth of a percent, the answer is 0%.
>>>
>>> No wonder the profession is in crisis.  So much time posting about {}s
>>> and so little about untested code.  (I have to take your numbers at face
>>> value -- I have no data at all.)
>>
>> I can't claim any references for the numbers either.  I just know
>> there is a great deal of code gets released and used without complete
>> test coverage.  Most of it gets tested reasonably, I expect.  But how
>> many people who check the result of "malloc" for a null pointer return
>> can honestly say they always use fault injection to test the code path
>> followed on allocation error?  (That is, of course, just one example.)
> 
> Yes, and IO errors can be particularly hard.  By the way, when I mean
> tested I don't necessarily mean automatically tested with a test suite,
> but I think programmers should test as much as possible even if that
> involves using a debugger to force an error return from a library
> function.

Agreed.  (In my type of work, automatic test suites can be very difficult.)

> 
> Anyway, as I said, I accept your depressing numbers.  What is odd, in
> the light of them, is how little talk there is here about testing code
> compared to the relatively frequent debates about ()s and {}s.

Maybe.  Perhaps we should have more threads here about testing (whether 
automatic or manual)?

It could just be that the parentheses and braces are easy to do - they 
have so little cost that if they have any potential gain in bug 
reduction, they are probably worth using.  And it is easy to make rules 
about them, which are then easy to follow.  Good testing is a /lot/ harder.

> 
>>>> This kind of thing has caused bugs that escaped into the wild - in
>>>> code that was reviewed, heavily tested, and used massively in large
>>>> numbers of systems.
>>>
>>> This kind of assertion is unhelpful without details.  There's no way to
>>> determine what really went wrong and what process or procedure would
>>> have prevented it.
>>>
>>
>> A famous example would be the "Apple goto fail" in their SSL/TLS
>> code. I assume (perhaps inappropriately) that Apple tested this code,
>> and it was certainly commonly used code.
>>
>> The relevant section of the code was
>>
>>      if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
>>          goto fail;
>>      if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
>>          goto fail;
>>          goto fail;
>>      if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
>>          goto fail;
>>
>> With a code formatting style that required braces on "if" statements,
>> that mistake would have stood out like a sore thumb.
> 
> Seriously?  That mistake does not stand out like a sore thumb?  I mean
> that almost literally.  Just a glance for a fraction of second and I am
> almost in physical pain.

It stands out to me too.  But obviously it did not stand out to the 
person who wrote it, or to the people responsible for reviewing it.

> 
> Anyway, if this is an example of what you meant, this code must have
> been "heavily tested".  Was it?  A whole chunk of code has no test
> coverage (the function continues, of course) even with no test harness
> to simulate errors.
> 
> This is a classic example of why goto is considered harmful.  The bug
> comes from the fact that the fail label (presumably) just returns err.
> Every place where you have
> 
>    label:
>        <code>;
> 
> in a C function you must check (and test) every place from which you can
> get here.  That's why I hate gotos so much and why I am cautious about
> breaks.  The pre-conditions for "<code>" are hard to determine.
> 

I agree.  goto makes it hard to trace the code flow backwards.

> Of course, no one determines pre- and post-conditions these days and I
> accept that that is now a lost art, but in my very limited experience,
> I've found more bugs from simple and informal reasoning about code than
> I ever found through testing.
> 

My university training put a lot of emphasis on pre- and post-conditions 
for functions, as well as variants and invariants.  While I can't claim 
to have done much formal (or even informal) proof of my code since I 
left university, these are always in my mind when I am coding.  But I 
think the majority of people who write software have never really been 
taught programming - most have at best been taught how to write code in 
C (or Java, or Python, or whatever) rather than the mathematical 
principles of programming.

[toc] | [prev] | [next] | [standalone]


#149897

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2020-02-09 21:50 +0000
Message-ID<874kvzl9bj.fsf@bsb.me.uk>
In reply to#149890
Again, forgive me for picking only one point to address...

David Brown <david.brown@hesbynett.no> writes:

> On 09/02/2020 16:35, Ben Bacarisse wrote:
>> David Brown <david.brown@hesbynett.no> writes:
>>> On 09/02/2020 03:07, Ben Bacarisse wrote:
>>>> David Brown <david.brown@hesbynett.no> writes:
<cut>
>>>>> This kind of thing has caused bugs that escaped into the wild - in
>>>>> code that was reviewed, heavily tested, and used massively in large
>>>>> numbers of systems.
>>>>
>>>> This kind of assertion is unhelpful without details.  There's no way to
>>>> determine what really went wrong and what process or procedure would
>>>> have prevented it.
>>>>
>>>
>>> A famous example would be the "Apple goto fail" in their SSL/TLS
>>> code. I assume (perhaps inappropriately) that Apple tested this code,
>>> and it was certainly commonly used code.
>>>
>>> The relevant section of the code was
>>>
>>>      if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
>>>          goto fail;
>>>      if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
>>>          goto fail;
>>>          goto fail;
>>>      if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
>>>          goto fail;
>>>
>>> With a code formatting style that required braces on "if" statements,
>>> that mistake would have stood out like a sore thumb.
>>
>> Seriously?  That mistake does not stand out like a sore thumb?  I mean
>> that almost literally.  Just a glance for a fraction of second and I am
>> almost in physical pain.
>
> It stands out to me too.  But obviously it did not stand out to the
> person who wrote it, or to the people responsible for reviewing it.

Well my point is that I don't really know what happened so I don't know
how good an example it is.

I am pretty sure that someone just "yanked" that line twice rather than
once (that's the Emacs term -- other editors are available) and my guess
is that the code never got more than the most perfunctory test and that
it was not reviewed at all.

If it was heavily tested and properly reviewed, those procedures need to
be looked at!

<cut>
-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#149899

FromBart <bc@freeuk.com>
Date2020-02-09 22:51 +0000
Message-ID<x200G.861064$GFe.306443@fx12.am4>
In reply to#149897
On 09/02/2020 21:50, Ben Bacarisse wrote:
> Again, forgive me for picking only one point to address...
> 
> David Brown <david.brown@hesbynett.no> writes:
> 
>> On 09/02/2020 16:35, Ben Bacarisse wrote:
>>> David Brown <david.brown@hesbynett.no> writes:
>>>> On 09/02/2020 03:07, Ben Bacarisse wrote:
>>>>> David Brown <david.brown@hesbynett.no> writes:
> <cut>
>>>>>> This kind of thing has caused bugs that escaped into the wild - in
>>>>>> code that was reviewed, heavily tested, and used massively in large
>>>>>> numbers of systems.
>>>>>
>>>>> This kind of assertion is unhelpful without details.  There's no way to
>>>>> determine what really went wrong and what process or procedure would
>>>>> have prevented it.
>>>>>
>>>>
>>>> A famous example would be the "Apple goto fail" in their SSL/TLS
>>>> code. I assume (perhaps inappropriately) that Apple tested this code,
>>>> and it was certainly commonly used code.
>>>>
>>>> The relevant section of the code was
>>>>
>>>>       if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
>>>>           goto fail;
>>>>       if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
>>>>           goto fail;
>>>>           goto fail;
>>>>       if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
>>>>           goto fail;
>>>>
>>>> With a code formatting style that required braces on "if" statements,
>>>> that mistake would have stood out like a sore thumb.
>>>
>>> Seriously?  That mistake does not stand out like a sore thumb?  I mean
>>> that almost literally.  Just a glance for a fraction of second and I am
>>> almost in physical pain.
>>
>> It stands out to me too.  But obviously it did not stand out to the
>> person who wrote it, or to the people responsible for reviewing it.
> 
> Well my point is that I don't really know what happened so I don't know
> how good an example it is.
> 
> I am pretty sure that someone just "yanked" that line twice rather than
> once (that's the Emacs term -- other editors are available) and my guess
> is that the code never got more than the most perfunctory test and that
> it was not reviewed at all.
> 
> If it was heavily tested and properly reviewed, those procedures need to
> be looked at!

Maybe it was tested, but the line accidentally got duplicated 
afterwards. That can still happen even with braces, but it would up as:

        if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) {
           goto fail;
           goto fail;
        }

Which doesn't affect the operation. A few things are like that in C, for 
example if you take the first two lines of that example, and someone 
accidentally added ";" at the end of the first:

        if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0);
            goto fail;

This one is a little harder to spot. Again you can employ special 
purpose tools, but the real culprit is the language design, which could 
have swept away all such problems by always requiring braces[*], or not 
allowing null statements consisting of a single semicolon.

([*] One possible exception might be for the else part of if-else, where 
either a compound or if-statement can be used. Otherwise, because C 
doesn't have a proper multi-branch if/elif form - unlike its 
preprocessor - it would mean writing the messy:

    if (c1) {
       s1;
    } else {
       if (c2) {
          s2;
       } else {
          s3;
       }
    } )

[toc] | [prev] | [next] | [standalone]


#149904

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2020-02-10 01:39 +0000
Message-ID<87sgjjjk4w.fsf@bsb.me.uk>
In reply to#149899
Bart <bc@freeuk.com> writes:

> On 09/02/2020 21:50, Ben Bacarisse wrote:
>> Again, forgive me for picking only one point to address...
>>
>> David Brown <david.brown@hesbynett.no> writes:
>>
>>> On 09/02/2020 16:35, Ben Bacarisse wrote:
>>>> David Brown <david.brown@hesbynett.no> writes:
>>>>> On 09/02/2020 03:07, Ben Bacarisse wrote:
>>>>>> David Brown <david.brown@hesbynett.no> writes:
>> <cut>
>>>>>>> This kind of thing has caused bugs that escaped into the wild - in
>>>>>>> code that was reviewed, heavily tested, and used massively in large
>>>>>>> numbers of systems.
>>>>>>
>>>>>> This kind of assertion is unhelpful without details.  There's no way to
>>>>>> determine what really went wrong and what process or procedure would
>>>>>> have prevented it.
>>>>>>
>>>>>
>>>>> A famous example would be the "Apple goto fail" in their SSL/TLS
>>>>> code. I assume (perhaps inappropriately) that Apple tested this code,
>>>>> and it was certainly commonly used code.
>>>>>
>>>>> The relevant section of the code was
>>>>>
>>>>>       if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
>>>>>           goto fail;
>>>>>       if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
>>>>>           goto fail;
>>>>>           goto fail;
>>>>>       if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
>>>>>           goto fail;
>>>>>
>>>>> With a code formatting style that required braces on "if" statements,
>>>>> that mistake would have stood out like a sore thumb.
>>>>
>>>> Seriously?  That mistake does not stand out like a sore thumb?  I mean
>>>> that almost literally.  Just a glance for a fraction of second and I am
>>>> almost in physical pain.
>>>
>>> It stands out to me too.  But obviously it did not stand out to the
>>> person who wrote it, or to the people responsible for reviewing it.
>>
>> Well my point is that I don't really know what happened so I don't know
>> how good an example it is.
>>
>> I am pretty sure that someone just "yanked" that line twice rather than
>> once (that's the Emacs term -- other editors are available) and my guess
>> is that the code never got more than the most perfunctory test and that
>> it was not reviewed at all.
>>
>> If it was heavily tested and properly reviewed, those procedures need to
>> be looked at!
>
> Maybe it was tested, but the line accidentally got duplicated
> afterwards.

That's just another way of saying that it (the code in question) was not
tested!

I agree that this seems very likely.  The code was probably tested at
various stages, but the code with the bug was not, possibly because no
one noticed a change had even happened (a finger fumble on save, maybe).

> That can still happen even with braces, but it would up as:
>
>        if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) {
>           goto fail;
>           goto fail;
>        }
>
> Which doesn't affect the operation.

Rather than mandate {}s all over the place, I would prefer to
concentrate on the procedures for version control and testing.  But
that's because I don't like visual clutter and I do like having reliable
procedures.

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#149910

FromDavid Brown <david.brown@hesbynett.no>
Date2020-02-10 09:55 +0100
Message-ID<r1r5qn$81d$1@dont-email.me>
In reply to#149904
On 10/02/2020 02:39, Ben Bacarisse wrote:
> 
> Rather than mandate {}s all over the place, I would prefer to
> concentrate on the procedures for version control and testing.  But
> that's because I don't like visual clutter and I do like having reliable
> procedures.
> 

My preference is to use /both/, so that mistakes are less likely to be
missed.

I don't like visual clutter either, but I don't see braces as visual
clutter - I see them as a simple and consistent way of arranging code
that works well with indentation.  But of course habit and familiarity
is a key part of what any one person finds "visual clutter".

[toc] | [prev] | [next] | [standalone]


#149911

FromBart <bc@freeuk.com>
Date2020-02-10 11:07 +0000
Message-ID<yPa0G.806802$CO7.489605@fx36.am4>
In reply to#149910
On 10/02/2020 08:55, David Brown wrote:
> On 10/02/2020 02:39, Ben Bacarisse wrote:
>>
>> Rather than mandate {}s all over the place, I would prefer to
>> concentrate on the procedures for version control and testing.  But
>> that's because I don't like visual clutter and I do like having reliable
>> procedures.
>>
> 
> My preference is to use /both/, so that mistakes are less likely to be
> missed.
> 
> I don't like visual clutter either, but I don't see braces as visual
> clutter - I see them as a simple and consistent way of arranging code
> that works well with indentation.  But of course habit and familiarity
> is a key part of what any one person finds "visual clutter".
> 

It /is/ extra clutter compared with some styles of block delimiting (as 
used in other languages not just C).

For example, having to write "} else {" instead of just "else" in 
patterns like this (exprs/statements not shown):

   if ( ) { } else { }        # C, 8 framing tokens

   if then else fi            # Algol68-inspired, 4 framing tokens

This is why it's tempting in C to just write:

   if ( ) else

when possible. It comes down to language design choices that were not 
the best.

[toc] | [prev] | [next] | [standalone]


Page 4 of 7 — ← Prev page 1 2 3 [4] 5 6 7  Next page →

Back to top | Article view | comp.lang.c


csiph-web