Code as if someone’s life depended on it.

Message for the day…

A useful technique I use to reduce the number of bugs in my buggy programs is to code as if someone’s life depended on them. When “it doesn’t matter,” it’s easy to avoid adding all the error checking.

But once you start looking at code as if it was mission critical, you start to see things differently and begin adding “useless” error checking. As long as you can afford the extra few moments to add the “useless” error checking, and as long as you have code space to hold the “useless” error checking, and as long as you have enough CPU cycles to run the “useless” error checking, you end up with a program that should be better,

Share and enjoy.

Star Laser Force laser tag in Houston

Anyone remember it?

https://arcadepreservation.fandom.com/wiki/Star_Laser_Force

Originally thought to have been the first laser tag arena, these days I believe we consider it the third.

Here are some memories from one of the players:

I post this now because I’d like to reach more folks who remember it. Maybe we can draw out details of the arena and fill in some missing memories.

Until then…

Life without the Cloud

Since this past summer, I have been without home internet. I previously went without phone and home internet for quite some time before, so it’s not nearly as shocking this time around.

It does make me realize how cloud dependent computing has become. Computers, in general, are far less useful without an internet connection. Today, so much syncing takes place automatically — online backups, Dropbox file sharing, photos in the Cloud, etc. It’s weird using a computer that doesn’t “magically’ have everything available that is available to my other devices.

Still, even when I had home internet, I still spent about 95% of time time on my iPad rather than the computers I have. I seem to only use them for heavy lifting these days, such as video or audio editing, website maintenance, and photo galleries.

How productive do you think you could be without internet access on your computer?

In other news, I have 28 draft articles going back to 2017 waiting for me to have time to complete them and post them here. Without internet, at least I have an excuse for not getting them done currently ;-)

Braces! Foiled again!

Here’s another quick C programming thing.

Consider the following code, which nest two for/next loops together. Notice the variable it uses for each one.

for (int i=0 ; i < 10; i++) // using i
{
    printf("%d\n", i);

    for (int i=0 ; i < 3 ; i++) // using i
    {
        printf ("   %d\n", i);
    }
}

What do you think it will print? Will this even work? Running it produces…

0
   0
   1
   2
1
   0
   1
   2
2
   0
   1
   2
3
   0
   1
   2
4
   0
   1
   2
5
   0
   1
   2
6
   0
   1
   2
7
   0
   1
   2
8
   0
   1
   2
9
   0
   1
   2

In C, you create a new instance (scope) of a variable “i” within the braces. The second for/next declares its own local i, and any references to i within those braces will be that second instance of i.

This is confusing, of course, but it works.

A “bug” could exist if the second scope forgot the “int”:

for (int i=0 ; i < 10; i++) // using i
{
    printf ("%d\n", i);

    for (i=0 ; i < 3 ; i++) // where's the int?
    {
        printf ("   %d\n", i);
    }
}

By forgetting that “int”, it re-uses the first instance of i, and does not do what was expected.

0
   0
   1
   2
4
   0
   1
   2
4
   0
   1
   2
4
   0
   1
   2
4
   0
   1
   2
4
...repeat...

This was based on something recently fixed in some production code at my day job.

So, yeah. Use different variable names and avoid this from ever happening.

Next, revisiting a recent post, also dealing with what braces do, I stumbled upon a much better reason to always put braces around things, even if it’s just one statement.

Suppose you had a simple DEBUG macro (this is not a good one, but pretend it is):

#define DEBUG(x) printf(x);

if (x==1) DEBUG("hello");

Looks fine! But if you decide to make the macro contain multiple statements, using the backslash character like this:

#define DEBUG(x) printf("ERROR!\n"); \ printf(X);

It now breaks. That macro changes the resulting code into something like this:

if (x==1) printf("ERROR!\n");
printf("hello");

Not what was expected. To solve this, the macro creator should have put the statements in braces like:

#define DEBUG(x) { printf("ERROR!\n"); \ printf(X); }

Problem solved. Assuming the macro creator did it that way.

So, to prevent things like this that look fine and work fine from doing neither, just get in the habbit of using braces even for one statement:

if (x==1) { DEBUG("hello"); }

Or just always do them in multiple lines:

if (x==1)
{
   DEBUG("hello");
}

…and you don’t ever have to worry about that again.

Until next time…

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.