Function names and “Clean Code”, part 2

See also: Part 1

Oh, the frustrations of obvious function names that don’t actually help.

LED1_On();
LED1_Off();
...
LED9_On();
LED9_Off();

First, it’s quite obvious that LED1_On() probably turns LED #1 on, and LED1_Off() turns it off. Simple.

But what is LED #1?

For most of my programming career, I have coded this way. You can always tell folks what that LED is in the commands… But then, of course, you don’t always do that everywhere it is used, and then if it is ever changed, all the old comments lie. (Thank you, Clean Code book, for making me fear comments.)

Today, I treat this kind of like how the OS-9 operating system treated devices… There is a device description (the thing that you are trying to access by name) and a device driver (the thing that controls the thing you are actually trying to access). Under OS-9, a hard disk might have been called “/h0” or “/h1”. A disk drive might have been “/d0” or “/d1”. The device drivers may have been some cryptic name with a chip number in it, such as “fd507” or “rb1003”. But that didn’t matter, because the used didn’t have to know and didn’t have to care. “/d0” was probably the main disk drive on any OS-9 system with a disk drive, regardless of what the actual underlying hardware was.

So for coding these days, I tend to write “low level” driver type functions like LED1_On() and LED2_Off(), and then wrap them in some clean code like:

void StatusLEDOn()
{
   LED1_On();
}

void StatusLEDOff()
{
   LED1_Off();
}

That adds a “useless” layer of code, but it keeps things nice and separate. If I see “StatusLEDOn()” in code, I can assume it probably turns on whatever the Status LED is. And if I see that function, I can determine that the Status LED must be LED #1.

And a good optimizer will likely just optimize these “useless” functions away, anyway.

Thanks to that stupid book, now when I see “ReadAI(2)” or “ToggleDO(5)” I just want to dive in and write wrapper functions to make that code look like “GetCurrentTemperature()” or “ToggleStatusLight()”.

I really need to go back and update all my code on GitHub some day…

Function names and “Clean Code”

At a previous job, I was introduced to the concept of “clean code.” As an embedded programmer, where we are often trying to squeeze extra bytes out of already optimized code, many of the principals of clean code do not apply.

But, in general, I like what I have read so far in this recommended book on the subject:

https://amzn.to/2KCtFy1 (affiliate link)

With this in mind, I wanted to ask a question about function names (whether they be in C, Perl, Java, or whatever).

In the past, I would write my functions using verb/noun, like this:

InitUserlog();
InitDisplay();
InitNetworking();

But after my exposure to object oriented programming, I learned about how classes and methods are used:

Userlog.init();
Display.init();
Networking.init();

This approach makes it very clean which class a function (method?) belongs to.

I started doing my C code similarly, letting the noun of the code lead:

UserlogInit();
DisplayInit();
NetworkingInit();

With all the Userlog functions starting with Userlog, I think it makes it clearer where things come from, and helps avoid collisions with outside code (or just code from another engineer on the same team).

With clean code, code should read more like English. Thus, using “InitializeUserlog()” is probably cleaner than “UserlogInit()”. But since you can’t do that with object oriented languages, perhaps writing backwards (Userlog.init(), UserlogInit(), etc.) is accepted due to the limitation of the language.

Indeed, “Userlog.lookupName()” seems less clean than “LookupNameInUserlog()”.

Perhaps I shouldn’t be doing this in C, since I *can* write the functions out more like proper English.

What do you think? Comments appreciated.

C and the dangers of memcpy()

Updates:

  • 2019-08-12 – Added note about using unions.

In the C programming language, memcpy (memory copy) is a function used to copy a range of bytes from one location in memory to another. I have used it often. Today, my boss mentioned something about not liking memcpy() because of all the dangers of using it. I understand that incorrect addresses, bad calculations, and simple omissions from a copy/paste can cause a memcpy() to have bad results. But, what’s the alternative?

He mentioned that he prefers to use C structures to copy data around, as opposed to using memcpy() to copy blocks of data.

Instead of doing this…

char Buffer1[64];
char Buffer2[64];

// Load Buffer1 with something.
strncpy (Buffer1, "Copy this string over", 64);

// Copy Buffer1 into Buffer2.
memcpy (Buffer2, Buffer1, 64);

That’s a simple, straight-forward example that seems hard to mess up. But doing something like this would be impossible to mess up:

typedef struct
{
    char Buffer[64];
} CopyStruct64;

CopyStruct64 Buffer1;
CopyStruct64 Buffer2;

// Load Buffer1 structure with something.
strncpy (Buffer1.Buffer, "Copy this string over", 64);

// Copy Buffer1 structure into Buffer2 structure.
Buffer2 = Buffer1;

Interesting. With properly defined structures, copying a block of data from one place to the other is done using code generated by the compiler.

(Update) And it seems I misspoke. He was actually talking about using unions, not structures. I’ve used unions as unions, but never for something like this. I did a similar test. (I realize there are several ways to declare a union, but I am using typedef so it looks similar to the above structure example.)

typedef union
{
    char Buffer[64];
} CopyUnion64;

CopyUnion64 Buffer1;
CopyUnion64 Buffer2;

// Load Buffer1 structure with something.
strncpy (Buffer1.Buffer, "Copy this string over", 64);

// Copy Buffer1 structure into Buffer2 structure.
Buffer2 = Buffer1;

Using union appears to work the same way, and since my example was not using structure elements, it seems to make more sense to do it that way. (End of Update)

I’m just now wrapping my brain around this, trying to figure out how this approach could be used to avoid using memcpy() and pointers.

What do you think? Am I on the right track to what he was talking about?

Until next time…

Braces! Foiled again!

Just a quick rant, based on how example code from a new compiler I am using is presented.

In C (and similar languages), it is very common to see simple logic presented in one line, such as:

if (AlertLevel == RED) TurnOnSiren();

That is simple to understand, and only takes up one line on the screen or a printout. However, at a previous job, our coding standard forbid that, and always required the use of braces around any actions of an “if”.

if (AlertLevel == RED)
{
   TurnOnSiren();
}

Now, ignoring style preferences of where the braces should go, the use of braces for something like this has some advantages when it comes to preventing potential bugs if this code is changed in the future.

In the case of the compiler examples I have been seeing, they show them without braces, such as:

if (AlertLevel == RED)
   TurnOnSiren();

For simple and short logic, this is no different than my first example — it just places the “what to do” stuff on an indented line after the “if”.

However, a common bug I see occurs when someone expands upon that like this:

if (AlertLevel == RED)
   TurnOnSiren();
   FlashRedLight();

In some languages, where program flow is determined by indentation, this would work. But in C, indentation does not matter. The above code would actually be processed as:

if (AlertLevel == RED) TurnOnSiren();

FlashRedLight();

The red lights would flash every time through, regardless of the status of AlertLevel.

Unintended consequences of not using braces, and using indents to format each statement on its own line.

By always using braces (even on simple one-statement things like this example), you avoid that:

if (AlertLevel == RED)
{
   TurnOnSiren();
   FlashRedLight();
}

Now we have the desired result, as adding new code or function calls inside the braces will work as we intended.

It’s 2019. The C Programming Language came out 47 years ago, and I still occasionally run into bugs caused by the lack of braces.

Thanks to a former job, I no longer make this mistake. I always use braces.

This has been a public service announcement of Sub-Etha Software.

Microsoft Visual Studio Code (PC/Mac/Linux) for CoCo cross development.

Microsoft Visual Studio Code for Mac (left) with extension to color code BASIC code for easy loading into Xroar emulator (right).

As mentioned elsewhere, there are some CoCo-related extensions available for the Microsoft Visual Studio Code editor. I did not realize that MS released this editor for Mac and Linux as well as Windows.

Here is the free editor:

https://code.visualstudio.com

Once installed, you can download (from within the editor) extensions.

Here are two extensions by Tandy UK — one for COLOUR BASIC and the other for 6309/6809 assembly:

https://marketplace.visualstudio.com/publishers/Tandy

There is another 6809 assembly extension available:

https://marketplace.visualstudio.com/items…

It colorizes files ending in .a or .asm. 

I don’t see many details about the Tandy UK ones, but I am indeed getting colorized BASIC keywords when I have a .bas file.

Yo ho, yo ho, a (video) pirate’s life for me…

The following is a reprint of an article I originally wrote around November 11, 2002 at 4:17:20 a.m. CST. Apparently.

From: Allen Huffman

Date: November 11, 2002 4:17:20 AM CST

Subject: Yo ho, yo ho, a (video) pirate’s life for me…

The 1990s.  You remember them, don’t you?  It was a time of amazing things such as the mainstream birth of “alternative” music. Records were being phased out with CDs in long boxes taking over. You remember long boxes, don’t you?  Blockbuster Video was gearing up to be the first movie rental store that would never be missing a title you wanted thanks to VideoCDs.  You remember VideoCDs, don’t you?

Ah yes, VideoCDs. If you are in Asia, you probably know exactly what a VideoCD is.  You may even have a collection of all the latest blockbuster movies in this format. But if you live in America, you may have only heard of VCDs from spam junk mail offering software to let you copy any DVD down to a CD.  A movie on a CD?  It’s true, honest, even if the spam offer isn’t.  Thanks to video piracy, a whole new generation is discovering the video format that could have (and probably should have) changed the way we watch movies.

Imagine this.  It’s the 1990s, and LPs have given way to a new digital format for audio: the CD.  A tiny disc is capable of storing an hour or more of excellent quality audio without any scratches, pops, wow or flutter. Die hard audio enthusiasts are about the only people not embracing this new format. Soon the expression “you sound like a broken record” is meaningless to an entire generation raised on digital audio.  Soon this technology was being applied to computers, allowing you to store entire encyclopedias on one disc!  Amazing. And, of course, we understood this was a read only format.  Writing your own CD was total fantasy. And besides, who in the world had 600 megabytes of stuff to store on one? Hard drives weren’t even that big yet!

Speaking of… Early multimedia computers were hardly impressive. One early attempt to bring multimedia to the masses was a machine made by Phillips called CD-i which stood for Compact Disc Interactive. Just as the audio CD had a standard (“red book”), so did CD-i.  The goal was to create a line of players that allowed you to insert a disc that contained multimedia — without needing a computer. The CD-i player shipped with an encyclopedia, and many games were available.  A player was about $1000 at first, and that still made it far cheaper than a home computer with CD multimedia support.  Sadly, CD-i never took off.  No one wanted a stand alone box to play games on CDs with. Imagine that.

Anyway, one of the CD-i standards is still found today — the Kodak Picture CD (back then under a slightly different name).  You could take a roll of film in for developing and get back a CD containing high resolution scans of your pictures. Over a decade later, this idea is actually starting to take off even though low cost digital cameras and scanners have greatly reduced market potential. But Picture CD not the important format — the important one was VideoCD: the VHS killer.

VideoCD would require a special hardware cartridge to be plugged in to the CD-i player.  This hardware allowed you to play up to 70 minutes of VHS-quality video from a standard CD.  (The cartridge handled something known as MPEG-1 video. Today almost everyone has heard of MPEG formats such as MP3s as well as DVD which uses MPEG-2.)  In a way, VideoCD is the father of DVD.  The DVD disc you see today has over 4 gigabytes of MPEG-2 video, while a VideoCD movie usually shipped on two discs with each holding up to 70 minutes of MPEG-1. But I digress.

A small selection of movies was available in VideoCD format in America.  Even as recently as 1996 you could still buy movies on VideoCD at Best Buy (as well as CD-i titles) but today the format is almost completely forgotten in America.  Why?  Because the thought of playing a movie on a CD was just silly.  Who wants that?  Ironically, a decade later a much more expensive technology (with “much better” rather than just “same or better” quality as VHS) did win the hearts of millions as DVDs became the fastest growing standard ever.  (Happy 5th birthday, DVD format!)

So was VideoCD just too early?  I think so.  Why did you mention Blockbuster at the start of this musing?  I was just about to get to that. Here is the part that makes me sad, folks. We lost out, big time, by VCD not taking off in America.  If consumers had embraced the format, we could have seen dedicated VCD players in the sub-$100 format long before low grade VCRs (with many more moving parts) ever made it there. Movies would have had instant access like an audio CD, and would never degrade.  And, here’s the fun part, companies like Blockbuster were talking about adding a satellite receiver to let them download and write (today we call it “burning”) your favorite movie to a VideoCD so you could rent any title you want. (Note: Later Blockbuster did experiment with making rental video games on programmable cartridges available this way.)

Long before the thought of high speed broadband internet access (and downloading illegal copies of the latest theatrical release) was even imagined, the rental industry had already found a way to embrace a new technology and make money off of it.  It was perfect.  Better than VHS quality, never needed cleaning, cheaper players (eventually) and movies that would cost less to produce than VHS (just look at the price of a blank CD today versus even the cheapest blank video tapes).  A missed opportunity.

So here I sit, wading through tons of junk mail and always finding an offer to “copy any DVD to CD” somewhere in the stack. The pirates have discovered a way to use something everyone else has forgotten. It seems it always works this way. After all, it was the pornography industry that had the most to do with the success of VHS in the first place, so I guess I shouldn’t be surprised.

The next time you sit down to enjoy the latest blockbuster movie on DVD, pause for a moment as you realize you could have been doing this a decade ago. The next time you go to rent your favorite title and it’s out of stock, think about the video store that could have been if only CD writers had existed and pirates were making use of the them to make the format popular…

Speaking of popular, you realize that CDs are now older than most cars, right? Twenty years is a very long time for any technology, so soon, when talking about how you used to rip tunes from CD, you may find yourself asking:

“You remember CDs, don’t you?”

Would you run modern OS-9 on a Raspberry Pi?

Today, Microware posted a survey on their Facebook group asking which model(s) of Raspberry Pi you’d be interested in running OS-9 on.

If interested, and you are on Facebook, drop by the group and respond to the survey:

https://www.facebook.com/groups/334403350011917/

I don’t know many details, but it seems that buying the hardware and OS-9 license should cost much less than what we paid to get it on a CoCo back in the day ;-)

Modern monitors that work with the CoCo 3!?!

In the 1980s and 1990s, there were many computers made that used a 15Khz analog RGB signal. These included the CoCo 3, Commodore Amiga, Atari ST, etc. There were a number of monitors to choose from to use on the CoCo 3, with one of the most popular being the Magnovox (remember them?) 8CM515. It supported RGB-A but also had composite audio/video so you could get the old CoCo 1/2 artifact colors when needed.

I thought the days of 15Khz was long gone. We have had a few solutions for hooking up a monitor to the CoCo 3, including an FPGA project, Cloud-9’s VGA converter, and the Switch-a-roo cable with a SCART converter box.

But Alexandre Souza on Facebook let me know they use all kinds of LCD monitors in Brazil, and pointed me to this list of modern monitors that still support 15Khz analog RGB:

http://15khz.wikidot.com/?fbclid=IwAR3S-JRwwEau0WsJsRTBXaNrgXIX92pYfdGPvt0D-CJpYPGnat2nD4A3h4k

One of the highly recommended monitors on the list is on Amazon for $139. It might take just as a cable to make it work with the CoCo, or possibly a bit of signal inversion (just like the old days).

Anyone know more on this?