Coding Style ... to encourage good practices

GoatGuy

New member
Hey there teensy fans.

Here is a snippet of code from the tutorial (8 bit) that I've reformatted into a format that has a lot of "tutorial advantages".
Clarity of form.

Code:
/* ---------------------------------------------------------------------- */
/* Set up constants to define pins.  Do this "at the top" so that it      */
/* flows thru the rest of the code parametrically.                        */
/* ---------------------------------------------------------------------- */
int redPin   = 12;
int greenPin = 15;
int bluePin  = 14;

/* ---------------------------------------------------------------------- */
/* Set the defined pins to OUTPUT mode, so they can be modulated by the   */
/* code herein.                                                           */
/* ---------------------------------------------------------------------- */
void setup()
{                
  pinMode( redPin,   OUTPUT );
  pinMode( greenPin, OUTPUT );
  pinMode( bluePin,  OUTPUT );
}

/* ---------------------------------------------------------------------- */
/* loop() is predefined to be repeatedly called, if defined. This code    */
/* sets each pin to a different analog value in [0 .. 255], and waits     */
/* 1/2 second (500 milliseconds) between each change.                     */
/* ---------------------------------------------------------------------- */
void loop()                     
{
  analogWrite( redPin,   30  ); delay( 500 );  /* dim red */
  analogWrite( greenPin, 200 ); delay( 500 );  /* bright green (on dim red = yellow-green) */
  analogWrite( bluePin,  40  ); delay( 500 );  /* dim blue (on above = washed out YG) */
  analogWrite( redPin,   150 ); delay( 500 );  /* brighter red (to make brighter yellow) */
  analogWrite( greenPin, 0   ); delay( 500 );  /* turn off green (for just slightly magenta) */
  analogWrite( bluePin,  250 ); delay( 500 );  /* kick up blue to blue purple effect. */
}

I've been a programmer / designer now for what, 45 years? Has it been that long? Yep. Since age 14. At first, like most-everyone, I tended to follow the programming style of whatever examples (or the famous Kerningham & Richie 'C' book) were at hand. However, in the intervening years, I've taken to using both line-oriented, indent-oriented formatting AND column oriented form.

It makes it so much easier to read the code, to discern in this case what-all is being attempted. Especially the analogWrite()... delay() repetitions in loop().

I recommend this format. It definitely aids both debugging the code, but also explaining to others how it works. Moreover, it doesn't take very much overhead to do, while you're entering code. In fact, it saves a LOT of time in many cases, both from squashing bugs that are hard to see otherwise, mistakes that you miss, and because single-lines can be copy-pasted, yet do multiple things.

Hope all y'all agree.
But if not, write back!

GoatGuy (first post)

PS: now that I've reviewed how this site reformats things, I see that all multiple-space-characters are chewed up. DARN! Ah... learned to use the [ code ] block. It preserves spaces.
 
Last edited:
Code:
  analogWrite( redPin,   30  ); delay( 500 );  /* dim red */
agreed - but I want to add, that it's not a good practice to use more than one instruction per line (delay... ) - and to comment obvious things ("dim red" or things like "x = 5; // set x to 5)
 
Hey there teensy fans.

Here is a snippet of code from the tutorial (8 bit) that I've reformatted into a format that has a lot of "tutorial advantages".
Clarity of form.

First, welcome, GoatGuy. I hope you find this a friendly interesting community.

Now, on to the subject you raised. Code formatting and style has been discussed to death on the net and at many workplaces. It's the stuff of flamewars like Vi vs Emacs, Macs vs PC, etc. Your chances of winning people over are slim. What people find most readable is whatever they've had the most practice with. If you like seeing code formatted a particular way, I suggest you use the indent utility (or similar) to format the code to your liking. If you find this stuff makes a big difference, maybe you'd enjoy learning some modern integrated development environments that do things like this automatically and help you find hard to spot mistakes. If you publish an open source project, you can set the style rules for your collaborators. Respectful coder compromise with their collaborators.

Personally, I think most of your suggestions are not worth the trouble, but I wouldn't fight you on them if I added a feature or fixed a bug in your code. Making projects work is the main thing that interest us here.
 
On style, and "getting it"

agreed - but I want to add, that it's not a good practice to use more than one instruction per line (delay... ) - and to comment obvious things ("dim red" or things like "x = 5; // set x to 5)

See... your point is pedantically defended without acknowledging the several points of readability and style that I made. ''Its not good practice'' is according to whom? My various CS teachers, some. Other programmers, some. Yet, in all the years of coding, no one found a way to defend:
Code:
analogOutput( pinRed, 44 );
delay( 75 );
analogOutput( pinGreen, 88 );
delay( 100 );
analogOutput( pinBlue, 255 );
delay( 250 );
analogOutput( pinRed, 0 );
delay( 275 );
analogOutput( pinGreen, 255 );
delay( 300 );
analogOutput( pinBlue, 128 );
delay( 450 );
over this:
Code:
  analogOutput( pinRed,     44 ); delay( 75 );
  analogOutput( pinGreen,   88 ); delay( 100 );
  analogOutput( pinBlue,   255 ); delay( 250 );
  analogOutput( pinRed,      0 ); delay( 275 );
  analogOutput( pinGreen,  255 ); delay( 300 );
  analogOutput( pinBlue,   128 ); delay( 450 );
It'd take quite the pendant to claim that the second block is harder to read than the first one. Or even just as hard. The point of vertical alignment, even tho' it costs a few typing seconds, is a matter of style, with the intent to increase readability of the code not just for the next bloke, but for one's self some later time when blocks are being borrowed and repurposed.

As to not commenting the obvious, I actually agree with you. The REASON I added those comments to the line(s) was because the snippet of code actually occurs on the PCJR website in the 8-bit tutorial page 4. To someone - a complete novice - its kind of satisfying to have little cheap explanations inline to explain what-all is going on.

Just saying.
GoatGuy
 
First, welcome, GoatGuy. I hope you find this a friendly interesting community.

...flamewars...

Personally, I think most of your suggestions are not worth the trouble, but I wouldn't fight you on them if I added a feature or fixed a bug in your code. Making projects work is the main thing that interest us here.

Thank you for the welcoming preamble. I didn't mean to start a flamewar.
The idea of using ''a formatter'' has a LOT of adherents; I have worked for many years in commercial large-staff coding environments.

Thing is, that not a single one of the formatters is smart enough to do what I was suggesting.
So, as I found, it became the almost universal response from people, Why would you want to make code that couldn't be reformatted by an auto-indenter? ...

Mostly it was because I detested having my code tastefully reorganized by every coder who set about making a change or two by using said reformatters without a thought in the world. Indeed: it was their coding style to open a chunk, and if it didn't appeal to their innate style-settings-are-mine 'sense', then they'd press F7 (or whatever their hotkey was) to reformat the whole thing to their liking.

This tho', in turn, produced all nature of problems for the project administrators and back end detectors-of-change, resulting in compilation changes galore over ... whitespace adjustments. So, in many cases, reformatting was banned. Of other peoples' code.

OF LATE - no longer working with a bunch of other opinionated peeps - I'm reverting back to my original multi-column-when-opportune formatting.
Other programmers have advised (if supported) inline functions so that the snippet above might become:
Code:
void analogOutputDelay( int pin, int value, int millisec )
{
	analogOutput( pin, value );
	delay( millisec );
}
...
...
{
	analogOutputDelay( pinRed,    44,  75 );
	analogOutputDelay( pinGreen,  88, 100 );
	analogOutputDelay( pinBlue,  255, 250 );
	analogOutputDelay( pinRed,     0, 275 );
	analogOutputDelay( pinGreen, 255, 300 );
	analogOutputDelay( pinBlue,  128, 450 );
}

Just saying. If one has the intent felt so strongly, that its good to make an inline function to accomplish putting-it-all-on-one-line for brevity and easy copy-paste, then I see little defense of not just doing so without the function, for small blocks of things that just happen to format well as in your tutorial's code example.

PEACE everyone.
If you don't agree ... it doesn't matter.
If you see the light, then consider what really are YOUR coding standards.
They're not written in stone.

GoatGuy
 
I'll admit, code like this makes the hairs on the back of my neck stand up:

if (constant == someVariableOrExpression) { /* do stuff */ }

Yeah, I know the idea is to guard against accidentally using the assignment operator rather than conditional compare. But that seems like a pretty poor trade-off when the result is difficult-to-read code. I believe in optimizing for ease of later looking at the code and quickly figuring out what it really does. Especially when the expressions aren't so simple, I tent to think to myself as I read "if something unknown is equal to this known quantity, then...."
 
Again welcome to the forum,

I have also been coding since the Ice Age and that was many decades ago...

What I have found over the years is you sometimes just have to go with the flow... That is I have worked with many groups, who for example argue about everything, including simple things like where do you put the brackets {}. I have seen at least three quote standards on this and many of them have very good reasons... I have alternated over the years between two of them:
Code:
if () {
  ....
}

or

Code:
if()
{
    ....
}

Both have arguments for and against...

So when I edit others people code, I try to adhere to whatever style they have... But sometimes we screw up.

Again my coding style has changed over the years. Example variable names. I used to use the convention that there was a standard prefix for each variable type, so you would have names like: abLine, which was an array of bytes. More recently have tried to go toward using some of the ROS coding standards: http://wiki.ros.org/CppStyleGuide

The place where things often get screwed up is with the simple things. In particular indenting. Some believe in using spaces, some believe in using tabs... Some indent by 2 some 3 some 4.
An interesting problem here is many people use editors who might decide to do things like automatically convert tabs to spaces or vice versa...

As for your code in the first listing. Personally I prefer using // comments versus /* */
Why? It is far too often I see block comments like you showed where over time they don't line up anymore anyway... So they add distraction.

I also personally don't see the need for spaces around () That is for me:
Code:
analogOutput( pinRed, 44 );
is not any better or worse than:
Code:
analogOutput(pinRed, 44);
But again if I edit your code I would try to maintain it.

Sometimes lining things up looks good and sometimes it may not...
Code:
int redPin   = 12;
int greenPin = 15;
int bluePin  = 14;

may be fine, but suppose you use more descriptive variable names like:
Code:
int state_of_converted_pins = 0;
int red_pin                          = 12;
int green_pin                       = 15;
int blue_pin                         = 14;

I also don't have any problem of you having the multiple statements on a line like you have as it is readable.

Like already mentioned, I would resist putting in the comments where are obvious, as often what happens is you copy and paste the line with the comment and then change the code and forget to update the comment...

So again I think your code looks great, but not sure I will fully adopt it. As I sort of mentioned. Right now I am playing around with a TurtleBot 3 with ROS so I am trying to adopt their coding style...

Again welcome!

And lets say there are maybe 30 of these... Then when you look at the code is the 15 on the green pin or line below or above it... It may not be obvious when you are glancing at the code.
 
curlies and such

Thanks - and as the first (or second?) post reply paraphrase said, “this is an endless source of flame bait”. Well, not flame bait, but controversy. I fully appreciate your examples. For me at least, it mostly comes down to “what does the text-editor support” (for indenting, especially curly braces). I'm a VI-kinda-guy, and modern vim has a bazillion :set… settings; one of which supports
Code:
if( isTrue )
{
   do something;
   do another thing;
}
, so whenever I get a new computer, I figure out how to cast vim into my liking. (Sometimes it is pretty non-obvious!). I too have seen - and participated - in endless discussion of the merits of indenting-or-not-indenting the first curly as in your examples. I too adhere to whatever the coder-before-me used as her preferred form.

I have to say, I'm pretty surprised at the genteel, unaggressive responses to my posts. Apparently good willed people lurk in these caves.

Thank all of you again.
GoatGuy

PS: I definitely agree about the futility of alignment of complex-named variable expression strings. However, because “complex is hard, so forget it” doesn't mean “then why bother for any string” either. IF there's an opportunity take it. Don't need to be a NAZI about it either. Insofar as I've ever determined, the whole topic of coding style is to aid-and-abet readability and clarity of intent. If we all agree to that, well then ... the field is wide open!
 
Last edited:
I led a team of 7 programmers in my own game development company for 12 years. I thought it was a great idea to implement a standard and have everyone stick to it, but it is impossible*. I learnt after several years to be happy at the end of the day if the code was concise and clear enough to follow by another of the team a year later, with enough comments to describe complex parts of the code. Proper indenting and layout for readability goes without saying of course.

I found that apart from that, you can't be too pedantic about individual style - especially when you are jumping between 3-4 languages and on a daily basis, each with their own quirks!

*Ok, not impossible - but ROI (due to time wasted) was just not worth it.
 
My first job review after college was on BASIC code - like I did before those 4 years: Was interpreted BASIC and to complete the project I needed more of that 64K RAM for code and every character counts.

"your code is poorly commented"

Here I was running a sealed washable remote terminal for graphic output in a penicillin powder filling room and logging the weights and giving stats there and in parallel on the PC for the process as controlled by the other half of the company - and to finish 'text' had to go to add code.

I never heard about any bugs or issues - so nobody but the Marketing Manager doing my review ever read the code or comments.

Having consistency is important - code shouldn't be cryptic or obfuscated.
 
I think a standard is a good idea, but defining a standard, and getting people to agree on it will be tough. I've been coding since BASIC, so I get what a lot of the people above have stated as well. I have my own "style/standard". Over the years, I have made it the standard for all the different programming languages. I even find myself following someone else's standards from time to time. Example would be a driver/library for a module that I find on Github, that someone started, and never completed. I will follow their standard while finish it up, and making it work, then when I add my own "functions" I then modify the entire thing to my standard. I always do a PR with their format, but continue on with my own fork with my formatting style after that. I do find myself over commenting a LOT. Sometimes I even put one liner jokes in there to see if anyone notices. I turn it into a game.

I think you have a good idea, but making it reality will be tough.
 
Back
Top