Avoid bit fields
Here in the struct named MyData we see an example of poorly done bit fields and the bad design practice of pre-planned improvements. The problem with MyData is that two of the variables have bit fields that cross 8-bit boundries. The variables data3, data4, and data5 are jammed into 32 bits so 8 bits could be saved into a reserve variable for some future use. I am writing this article because I worked on code like this that is over 20 years old, so the 8 bits in reserve sat unused all these decades. Crossing 8 bit boundaries meant that data4 and data5 could not use the regular byte swap software like bswap_16(x) or bswap_32(x) (from /usr/include/byteswap.h)
struct MyData
{
UINT8 data1;
UINT8 reserve;
UINT16 data2;
UINT32 data3 :6;
UINT32 data4 :12;
UINT32 data5 :14;
};
See that data3 is 6 bits, which fits into a UINT8; data4 fits inside 16 bits, as does data5. A better design is struct MyImprovedData, shown below.
struct MyImprovedData
{
UINT8 data1;
UINT8 data3;
UINT16 data2;
UINT16 data4;
UINT16 data5;
};
Both structs are 8 bytes, but the second does not waste space with the unused "reserve" and also does not use bit fields that adversely impact portability and maintainability. Let me emphasize this: avoid bit fields to improve software maintainability.
A word about UINT8, UINT16, and UINT32. These are typedefs for the C data types.
Writing Code that Isn't Needed
Page 24 of Code Simplicity: The Fundamentals of Software by Max Kanat-Alexander has a section entitled "Writing Code that Isn't Needed." If you try to write code anticipating future changes, you will be wrong and you will need to fix your incorrect design. You might as well wait until you need to make the change and do it right. This is similar to a design rule called YAGNI, "You ain't gonna need it."
Contorting struct MyData in order to set aside an 8 bit reserve field that was never needed is a flaw worth avoiding in your code.
I will go a step futher and suggest you avoid using bit fields if you can. Decades ago memory was a scarce resource. Today memory is a plentiful resource and programming manpower is the scarce resource.
Robert
No comments:
Post a Comment
Comments require my approval before they appear. Be patient. It will take a day or two for your comment to appear.