[net.lang.c] C Programming Style -- New thought

freeman@spar.UUCP (Jay Freeman) (07/24/85)

References:

[Fools rush in where even the line-eater fears to tread]

I find that one of the things that most affects my personal choice of
program-formatting style is the number of lines on the console I work at.
Most of my C coding is done sitting in front of old-style displays of 24 by
80 lines.  I find it very valuable to be able to see all of a function (or
at least all of a {} block) at once:  Therefore, I favor styles such as

    if( (foo = bar( baz )) != ERR ) { ...    /* style A */

over

    foo = bar( baz );                        /* style B */
    if( foo != ERR ) { ...

when useful to save lines.  If the lines saved by using style A instead of
style B, make the difference between having all of a block on screen at once
and not; then I consider the additional complexity of style A to be worth it.

(And of course, there is ...

    foo = bar( baz ); if( foo != ERR ) { ... /* style C */

which I mention for completeness but consider a loser over (under?) style A.)

My point is not to tell you all how to do it, but merely to emphasize that
screen size imposes a tradeoff among different sources of
incomprehensibility.

A related issues is whether it is "worth it", in the same tradeoff, to have 
an extra line for '{' or for '}'.  (My personal opinion is "no" for the
former and "yes" for the latter.)

Incidentally, I avoid printouts wherever possible in developing code:  I use
them only when I cannot get to a terminal for some reason -- I cannot
imagine circumstances in which my preference would be the other way around.
(Well, maybe 300 baud ...)
-- 
Jay Reynolds Freeman (Schlumberger Palo Alto Research)(canonical disclaimer)

nather@utastro.UUCP (Ed Nather) (07/24/85)

> I find that one of the things that most affects my personal choice of
> program-formatting style is the number of lines on the console I work at.
> Most of my C coding is done sitting in front of old-style displays of 24 by
> 80 lines.  
> Jay Reynolds Freeman (Schlumberger Palo Alto Research)(canonical disclaimer)

I assume this means you "write code" directly at a terminal, using a text
editor, instead of the "venerable, traditional" way of writing it on paper
first, with a pencil (and a *large* eraser), and then entering the stuff
aftwerwards.

General question: does anybody "write code" on paper first any more?
-- 
Ed Nather
Astronomy Dept, U of Texas @ Austin
{allegra,ihnp4}!{noao,ut-sally}!utastro!nather
nather%utastro.UTEXAS@ut-sally.ARPA

gwyn@brl-tgr.ARPA (Doug Gwyn <gwyn>) (07/25/85)

> General question: does anybody "write code" on paper first any more?

Probably not many (except in DP shops that are way behind the times),
in the sense of preparing code that can then be transcribed by a
"keypunch operator".  I have seen a lot of people who should know
better try to DESIGN their code while they are entering it..

mjs@eagle.UUCP (M.J.Shannon) (07/25/85)

> General question: does anybody "write code" on paper first any more?
> -- 
> Ed Nather

I used to "do it" on paper as recently as a year or so ago, but have succumbed
to the paperless age.  For new programs, I now take a top-down approach,
entering a skeletal main() which either mucks with arguments itself or calls a
routine to do so.  Then it calls the main function of interest.  This routine
is then coded as was main(), mostly a skeleton detailing the algorithm, with
functions called for operations I haven't yet defined.  At this point, most of
the data structures are defined (modulo choices of storage management, such as
whether to use arrays, linked lists, quadtrees, etc.), since I've outlined the
algorithm sufficiently to understand what data types are involved.  My
experience with this method indicates that main() only changes to account for
changes in options or dealing properly with multiple file arguments, etc.  As I
discover "holes" in the algorithm, appropriate code is added, then the low-
level routines I used are defined.  I find this to be a rather effective method
for constructing programs -- more so than pencil & paper because I can see the
current version of the algorithm (usually on one screen) without having to
decipher my illegible scribbling over holes in the paper (from excessive
erasing).  Hope this helps some of you out there.  It has helped me (the
method, not this posting!).  Comments appreciated, flames ignored.
-- 
	Marty Shannon
UUCP:	ihnp4!eagle!mjs
Phone:	+1 201 522 6063

john@frog.UUCP (John Woods) (07/25/85)

>>I find that one of the things that most affects my personal choice of
>>program-formatting style is the number of lines on the console I work at.
>>Most of my C coding is done sitting in front of old-style displays of 24 by
>>80 lines.  
> 
> I assume this means you "write code" directly at a terminal, using a text
> editor, instead of the "venerable, traditional" way of writing it on paper
> first, with a pencil (and a *large* eraser), and then entering the stuff
> aftwerwards.
> 
> General question: does anybody "write code" on paper first any more?
>
Yes.  I prefer to, because it matches the way I think better.  However, this
(I feel) *increases* my desire for terseness.  Additionally, once I have typed
something in, I am more comfortable staring at hardcopy that a terminal
screen.  But once again, the more that is packed onto the page READABLY, the
better I like the code (and remember, you can't run GREP(1) on paper (yet)).

As an example:  the recent BYTE article on the TRAVESTY program (a few months
back) included a PASCAL program with a doubly nested loop, which had to use
a logical variable to escape from the inner one (I believe that that required
a double test in the while).  I recoded it in C, and came up with half the
number of lines, SIMPLIFIED IT TO A SINGLE LOOP using "C ``tricks''", and
came up with what I felt was vastly more readable code:  the whole function
"fit in my mind" at once.

The PASCAL program was not necessarily badly written; it was probably textbook
quality (not saying much :-).  However, readability is in the eye, and the
mind, of the beholder.

Who would you rather listen to, someone who gives an hour-long speech in
the 1000-word Basic English subset, or someone who uses the full power of
English to eloquently say the same thing in 5 minutes (without using archaic
words not in use for 300 years, note)?


--
John Woods, Charles River Data Systems, Framingham MA, (617) 626-1101
...!decvax!frog!john, ...!mit-eddie!jfw, jfw%mit-ccc@MIT-XX.ARPA

tmb@talcott.UUCP (Thomas M. Breuel) (07/26/85)

> > General question: does anybody "write code" on paper first any more?
> 
> Probably not many (except in DP shops that are way behind the times),
> in the sense of preparing code that can then be transcribed by a
> "keypunch operator".  I have seen a lot of people who should know
> better try to DESIGN their code while they are entering it..

Several computer scientists have come up with program design languages.
They are usually derived from programming languages like ALGOL or PASCAL
and (well, they can't enforce it anyway) allow a lot of syntactic and
semantic freedom, but are intended to cause you to think of your problem
in a structured manner. You can basically do the same thing by using
your favourite programming language and mixing it with natural language,
e.g.:

	while(there are still elements in the set) {
		pick an element;
		check for membership in exclusion set;
		if(not member of exclusion set) {
			...

There have been many attempts at enabling people to do program design
at the terminal, but none of them were really successful. A programming
language called 'ELAN', for example, was designed for (interactive)
top-down programming by allowing you to specify your programs in a
mixture of natural language and PASCAL, and then to resolve the natural
language parts by macro expansion. Object oriented systems and LISP
machines are other such examples of programming environments that are
supportive of interactive program design.

A good programming environment and a suitable language can help to make
interactive program design less of a disaster; most of the time the
results are pretty awful, though (look at UN*X sources -- at least I
think that that's what's wrong with them). 

It is very tempting just to sit down and 'hack something together', 
in particular if you are writing in 'C' on a UN*X system, but
if you really care about a program, I would recommend to sit down and
think about it for a long time, start scribbling ideas on paper, and
gradually try to implement this or that module. Often you still need
several tries to get it right.

					Thomas.

moss@BRL.ARPA (Gary S. Moss (AMXBR-VLD-V)) (07/26/85)

: General question: does anybody "write code" on paper first any more?

Sure, FORTRAN programmers and any one else who writes code where one must
span many pages to figure out what is happening.  You can always spot such
a person by the huge stacks of printouts on their desk because you also
need to spread it out to read it.

Of course this is just a stereotypical generalization.  Even tight code is
easier read when you can see several pages at once, its just that for me,
the need to GREP for stuff supercedes it.

Typing ability probably has a lot to do with it to.  If you can write with
a pencil faster, and YOU can read YOUR writing, knock yourself out (of course
eventually someone has to type it in, seems like a redundant exercise).

-moss

edg@well.UUCP (Ed Greenberg) (07/26/85)

In article <408@utastro.UUCP>, nather@utastro.UUCP (Ed Nather) writes:
> 
> General question: does anybody "write code" on paper first any more?
> -- 

I start to write functions on paper, but you can't use insert
functions on paper!  When I start to stick things in above, I
usually go to the terminal.

I DO write pseudocode on paper though.  Sometimes on index
cards.

			-edg

{hplabs,dual,ptsfa}!well!micropro!edg

vilot@gsg.UUCP (Mike Vilot) (07/26/85)

	I think this sort of discussion is useful, although a few
replies have degenerated into unhelpful nit-picking.  One thing we could
all use is a clearer definition of terms.  An excellent reference on
this topic is:

	Writing Efficient Programs
	Jon Louis Bently
	Prentice-Hall, Inc, 1982

Relevant topics include: defining the nature of the problem,
establishing the context, offering (language-independent) transformation
rules, and commenting on system-dependent issues.  It's a short book
(170 pp, including the index -- shorter that K&R), and it's easy to
read.
-- 
Michael J. Vilot			vilot@wang-inst		(CSNET)
General Systems Group			decvax!gsg!vilot	(UUCP)
51 Main Street				MVilot@ECLB		(ARPA)
Salem, NH  03079

chris@umcp-cs.UUCP (Chris Torek) (07/27/85)

>Typing ability probably has a lot to do with [programming on paper]
>to [sic].

Could be; I never write actual code on paper, and I type MUCH faster
than I write (I type reasonably quickly and write excruciatingly
slowly)....

However, I don't think that writing code on paper gains you much
if anything.  The key to writing good code is to have a clear
understanding of the algorithm(s) involved.

In some cases I need to do a complete rewrite after I've got
something working, once I know what I did wrong the first time
around....
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 4251)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris@umcp-cs		ARPA:	chris@maryland

chuqui@nsc.UUCP (Chuq Von Rospach) (07/27/85)

In article <408@utastro.UUCP>, nather@utastro.UUCP (Ed Nather) writes:
> 
> General question: does anybody "write code" on paper first any more?

I use paper for any non-trivial design, and usually find myself going
through three or four circuits fleshing it from something resembling
pseudo-code to something resembling C. Even better, when I'm actually in my
office, is my white board -- I don't know how people lived without them.
-- 
:From the carousel of the autumn carnival:        Chuq Von Rospach
{cbosgd,fortune,hplabs,ihnp4,seismo}!nsc!chuqui   nsc!chuqui@decwrl.ARPA

Your fifteen minutes are up. Please step aside!

david@ecrhub.UUCP (David M. Haynes) (07/28/85)

> General question: does anybody "write code" on paper first any more?
> -- 
> Ed Nather


Frankly, I'm surprised, aren't C and UNIX enough such that the
code writes itself? {-;
-- 
--------------------------------------------------------------------------
						David M. Haynes
						..!utzoo!ecrhub!david

"I am my own employer, so I guess my opinions are my own and that of
my company."

peterc@ecr2.UUCP (Peter Curran) (07/28/85)

Ed Nather asks if anyone still writes code on paper.

I most certainly do.  And hack it and fiddle it and juggle it until
I am satisfied that it accurately reflects the abstractions I am trying
to express before typing it in.  I also make listings fairly regularly,
so I can assure myself that I haven't lost the forest in the trees (of
course, I might lose the trees in the paper :-).)  When I have worked
with code that was developed without listings, I usually find it makes
sense in small (e.g. screen-sized) segments, but the large-scale flow
is almost incomprehensible.

Since I've started this, I might as well add the the general commotion...

I think it is ridiculous to discuss the "readability" (really I mean
"understandability") of isolated lines of code.  Any code is unreadable
without some training (give your most readable example to an English
major), and quite easily readable with a bit of training - and no doubt
the training varies a little bit with the language, the style, etc.

The concern should be with global readability.  I pay particular attention
to two aspects of this - program organization, and commenting.

Programs should be organized as functions, each with a simple purpose.
Generally speaking, that purpose can be expressed in a single sentence,
having one of three forms - "do this," "do this to that" or "do this to
that using this."  Using the well-known result from cognitive psychology,
the function should consist of seven plus-or-minus two "steps."  A "step"
is not well defined, but I find it averages about 4 lines of code.
Being somewhat weak-minded, I also aim for about 5 steps whenever possible.
By a remarkable coincidence, allowing for a blank line between each step,
this results in a typical function occupying 5*4+4 = 24 lines - a screenful.

Now to commenting.  Comments should first state the purpose of the function,
then give the steps that are being performed (i.e. the abstractions that the
code is realizing).  If there are comments at all in a piece of code, they
usually tend to describe the realization.  Given the abstraction that a few
lines of code are realizing, I can usually understand the code.
However, it is much harder to figure out the intended abstraction, given
an understanding of the realization.  And understanding the abstraction is
essential to understanding the next-higher-level abstraction (i.e. the
function that calls the one being studied.)

bc@cyb-eng.UUCP (Bill Crews) (07/29/85)

> A related issues is whether it is "worth it", in the same tradeoff, to have 
> an extra line for '{' or for '}'.  (My personal opinion is "no" for the
> former and "yes" for the latter.)

Although most programmers in the early sixties used horizontal white space
very little, rather typing "i=i+1" into their Fortran compilers, most today
seem to value horizontal white space and thus use it ("i += 1").  I think
this is a significant, though small, advance.  It does, however, cause the
right margin to become more of a problem.

I think vertical white space is also useful in achieving greater readability.
When reading code, especially code which is unfamiliar and uncommented, breaks
at logical intervals (before for statements, around comments, etc) are *very*
valuable.  Also, putting the { on its own line allows the { and } to be
aligned and likewise adds white space.  Clearly, the bottom edge of the screen
or printed page becomes more of a problem.

> Incidentally, I avoid printouts wherever possible in developing code:  I use
> them only when I cannot get to a terminal for some reason -- I cannot
> imagine circumstances in which my preference would be the other way around.
> (Well, maybe 300 baud ...)

I find 24 x 80 to be a quite small and confining window.  Try using Star- or
Sun-like screen some time.  They can spoil one easily.  Since I don't have one
myself, I get listings more often than I would otherwise.  Perhaps one day soon
we'll be freed from this norm form the past (sigh).
-- 

  /  \    Bill Crews
 ( bc )   Cyb Systems, Inc
  \__/    Austin, Texas

[ gatech | ihnp4 | nbires | seismo | ucb-vax ] ! ut-sally ! cyb-eng ! bc

jjd@wlcrjs.UUCP (Joe Durnavich) (07/29/85)

>> General question: does anybody "write code" on paper first any more?
>>
>Yes.  I prefer to, because it matches the way I think better...
>Additionally, once I have typed something in, I am more comfortable
>staring at hardcopy than a terminal screen. 

Personally, I feel that writing code on paper first is like writing
a letter on paper and then typing it into a word processor: a duplication
of effort.  I always argued with my teachers in school that the time
spent writing out the program (in addition to the typed in one) would 
be much better spent learning better structure techniques, new algorithms, etc.

					Joe Durnavich
					ihnp4!wlcrjs!jjd

-------------------------------------------------------------------------------
No part of this message may be reproduced, stored in a retrieval system, or
transmitted, in any form or by any means, without the permission of the author.
-------------------------------------------------------------------------------

bc@cyb-eng.UUCP (Bill Crews) (07/29/85)

> . . .
> if you really care about a program, I would recommend to sit down and
> think about it for a long time, start scribbling ideas on paper, and
> gradually try to implement this or that module. Often you still need
> several tries to get it right.

I like white marker boards, myself.  They're so ERASEABLE!  You can let it
evolve into what you really want.  After all, design is largely an iterative
process.  Besides, the whole development team can walk into you office, read
it, pontificate upon it, and help it evolve.

I'm not sure why I've gotten so averse to using paper for anything other than
scratching notes, like hex addresses.  It's like if I write my ideas on paper,
they are lost forever there; they can't be melded, shaped, and transformed
into grander things.  Not without retranscription, anyway.  Maybe if I got
some superfast pen . . .
-- 

  /  \    Bill Crews
 ( bc )   Cyb Systems, Inc
  \__/    Austin, Texas

[ gatech | ihnp4 | nbires | seismo | ucb-vax ] ! ut-sally ! cyb-eng ! bc

franka@mmintl.UUCP (Frank Adams) (07/29/85)

In article <241@frog.UUCP> john@frog.UUCP (John Woods) writes:
>As an example:  the recent BYTE article on the TRAVESTY program (a few months
>back) included a PASCAL program with a doubly nested loop, which had to use
>a logical variable to escape from the inner one (I believe that that required
>a double test in the while).  I recoded it in C, and came up with half the
>number of lines, SIMPLIFIED IT TO A SINGLE LOOP using "C ``tricks''", and
>came up with what I felt was vastly more readable code:  the whole function
>"fit in my mind" at once.


If you simplified it to a single loop, it sounds like you changed the
algorithm.  What happens if you try to reconvert to PASCAL without adding
back the extra loop?  If this isn't possible, just exactly what "tricks"
did you use?

franka@mmintl.UUCP (Frank Adams) (07/29/85)

I no longer write code on paper first; this changed at the time I first
got access to a full screen editor.

The main advantage of writing it down first is that is gives one a second
chance to look over the code and notice mistakes.  This reason is less
significant for me than it used to be because (1) I make fewer mistakes
than I used to, and (2) I gain the same benefit (plus others) by writing
a design specification.

Usually, I use a printed listing, except for very short code (fits on a
screen) (previously, I had a 43 line screen; now I'm back down to 25.
Everything else is better now, but I miss the big screen.  Sigh.)  Using
a listing doesn't keep me from using grep; I do both.

root@bu-cs.UUCP (Barry Shein) (07/31/85)

Re: White space in programs...

I remember Alan Perlis saying one night that he disliked Pascal-like
languages (that is, languages with an indenting style) because when you
listed them on the screen the screen was mostly covered with white space
and hence minimized information transfer.

As I remember he went on to speak about a 1000 line APL program which
was a Fortran compiler, that was 132 cols of APL per line, he liked to
give it to people to modify (I think that was at Yale, Yalies?)

There's no accounting for taste.

[in all fairness this is out of context and more than a few years old
and from my memory although I don't think it is a gross
misrepresentation.]

	-Barry Shein, Boston University

P.S. Hint: don't bother quoting this and taking it apart point by point.

ludemann@ubc-cs.UUCP (Peter Ludemann) (08/01/85)

In article <1017@umcp-cs.UUCP> chris@umcp-cs.UUCP (Chris Torek) writes:
>>Typing ability probably has a lot to do with [programming on paper]
>>to [sic].

Writing programs is easy.  Designing systems is hard.  The trouble
is, lots of people who can knock off 1000-liners on their terminals
try to do 20000-line systems the same way.

The best thing for programming is a tilting chair, a cup of coffee
and a desk to put one's feet on (preferably with an interesting view
out the window) while the brain percolates ids.  This assumes
that you've managed to figure out what your users want.

dbmk1@stc.UUCP (Derek Bergin) (08/01/85)

In article <3035@nsc.UUCP> chuqui@nsc.UUCP (Chuq Von Rospach) writes:
>Even better, when I'm actually in my
>office, is my white board -- I don't know how people lived without them.

They used blackboards ???  :-)


Regards
  Derek

!seismo!mcvax!ukc!stc!dbmk1

I used to think I was expressing an opinion - but there again people used
to think the world was flat.

chris@umcp-cs.UUCP (Chris Torek) (08/05/85)

In my everpresent zeal to prevent misquoting :-), I must note that
in the text quoted below, the >> shows that I was quoting someone
else (the bracketed text is the only part that is mine).  I was
actually pointing out that good programming is not really a matter
of where code is first written, be it paper, CRT, or runes engraved
in stone.

	From: ludemann@ubc-cs.UUCP (Peter Ludemann)

	In article <1017@umcp-cs.UUCP> chris@umcp-cs.UUCP (Chris Torek) writes:
	>>Typing ability probably has a lot to do with [programming on paper]
	>>to [sic].
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 4251)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris@umcp-cs		ARPA:	chris@maryland