TweetFollow Us on Twitter

January 92 - Double Dutch C++ Coding Style

Double Dutch C++ Coding Style

Matt Stibbe

Hungarian notation, invented by Charles Simonyi, is popular among some PC programmers. And Macintosh programmers, led by Apple itself, have evolved an ad-hoc style guide for Mac programs.

The importance of code style guidelines, of whatever kind, is growing in proportion to program size and complexity. This article presents a style guide based Apple's informal style guide and the sterner discipline of Hungarian. I'll refer to it as "Double Dutch," continuing the tradition ironic national references (I am half Dutch). It is particularly aimed at C++ users, but should be applicable to other 3rd generation languages.

Theory

The fundamental principle of Double Dutch is that the form of variable and function names follow their function.

An example is iCCh, which is read as an integer counter of characters and can be broken down as: [i] betokens an integer value, [C] indicates a counter of some kind, and [Ch] is the tag for a character value (a char) used here as a method mnemonic.

In function (or method) names, the form is similar. For example, iCCh=iGetLengthSz("filename"); is parsed thus: [i] again an integer value but this time indicating the functions return value; [GetLength] a natural language transitive verb indicating the functions operation; and [Sz] a tag for a zero terminated string (a C style string) which is the function's parameter-in this case, the file name.

It conveys a lot of information in a concise, formal and non-arbitrary way, but it isn't immediately readable. It is this apparent opacity, not Simonyi's nationality, that gave Hungarian notation its name.

Why go to such lengths to write apparently unreadable code? Because most programmers are born optimists. They tend to underestimate the length of a project, the complexity of their code, and the number of bugs in it.

A good style convention can bring estimates closer to reality. Brooks in "The Mythical Man Month" proposes a scheduling scheme of 1/3 planning, 1/6 coding, and 1/2 testing. Code conventions benefit each of these stages.

The planning stage usually involves constructing what might be termed a data dictionary-a class hierarchy containing data and methods. Double Dutch works best if the data formats are defined before coding begins. It provides a rigorous way to identify types, data structures, and functions in advance.

During coding, it enforces a close correspondence between a formal specification and implementation. Having a formalized way of writing variable and function names helps late-night coffee-assisted memories. It helps you avoid semantic contradictions like the one between "DisposPtr" and "DisposeControl," where one is written with an abbreviation and an 'e', the other not.

Simonyi and Heller talk of "type calculus" in their August 1991 Byte article. This is a mental discipline that is aided by Double Dutch style notation. The function and variable examples shown above provide a trivial example because the leading 'i' in iCCh [variable type] corresponds to the leading 'i' [return value] in iGetLengthSz(...). Type calculus comes into its own with the complex pointer arithmetic that C++ sometimes introduces. For example, pCh is a pointer to a character. Therefore, the 'p' component carries a memory of the original definition "char*" with it, making it easier to remember when to deference it.

In the prehistoric days when C compilers did not do much-or any-type checking, type calculus was helpful in tracking down some bugs. Nowadays, type calculus is still useful as another way of reviewing code during the testing phase-it complements dry runs, source level debuggers, compiler error messages, and encoded checks by providing a formal way of comparing the expectations of the code to runtime reality.

Double Dutch conventions also help overcome typical programming problems such as arbitrary abbreviations, inconsistency, sloppiness, large code atrophy, and "neat hack"-ism. The last two need some explanation.

Large code atrophy is a phrase I use for the naming and style problems that arise in large programs. For example, data type is defined in one header file. Later, a similar one gets defined in another file because the original has been forgotten or ignored or because it bears a name that wrongly suggests it doesn't apply to the situation.

"Neat-hack-ism" is the tendency among some C and C++ programmers to generate incomprehensible "write-only" code because it is a "neat hack." Embedding context, structure and purpose information into variable and function names can alleviate this kind of obfuscation. These problems are magnified when you work across platforms and when several programmers work on one project.

Programmers new to Double Dutch style tend to object to it on grounds of readability, inflexibility, and "cramping my style." The first two are valid objections, the latter mere prevarication. It's true that a program written in this style looks daunting, but then any high level language looks daunting to a non-programmer. Once the simple format is learned, a quick reading of a Double Dutch program yields a more comprehensive understanding of a piece of code. It is simply a matter of learning how to parse the names, and understanding the data structures unique to the program. This is what anyone has to do with a new program.

The accusation of inflexibility comes from the nuisance of updating variable and function names each time you change a type. In our example, if the programmer decided that a "long" rather than an "int" counter was required, every instance of the variable would have to be changed to lCCh, and the function to lGetLengthSz(...). This is a pain, even with global search and replace. In its defense, this change might draw attention to any dependence on an int counter.

C++ adds its own problems to programming by making it easier to write obscure code. Goldsmith and Palevich argue convincingly against frequent use of overloading and default arguments, and in favour of using strong type checking. A Double Dutch style complements this by expressing these self-imposed restraints in the code itself. Overloaded functions can be expressed without ambiguity in Double Dutch by changing the tags of the parameters or return value. For example, lGetLengthSz and lGetLengthFp might return the length of a file, but one takes a string and the other a file pointer as a parameter.

Implementation

Name construction

The centerpiece of Double Dutch is name construction. A name contains up to four component parts-the scope, type, qualifier and mnemonic-in the form [scope][type[s]][qualifier][mnemnonic].

Any or all of the parts can be omitted. Think of the name as an address-the more information that is added, the clearer the destination becomes. Each component begins with a capital letter. Variable names begin with a lower case character, function names begin with a capital letter. Underscore characters are not used.

Double Dutch is applied to function or method names thus: [Return Type][Mnemonic Action(s)][Parameter Types], where the first is the return value of the function, "Action" is a description of the action of the function or method that may be transitive (eg "print" or "find"), and where parameters lists the type tags of formal arguments. In grammatical terms, the parameters are the objects of the verb.

Scope

The scope indicates the provenance of a variable. Function names don't really need scoping as C++ enforces various kinds of scoping information. A static member function is prefixed by its class name (eg TScreen::Draw()), and other member functions have a "parent" object (eg theScreen->Draw()). The idea of scoping a variable draws on Apple's conventions, as embodied in MacApp.
theA function or method arguments, for example lGetLengthSz(char* theSz).
fA local or member variable, for example class TClass {int fI;};
kA constant defined using #define.
cA constant defined using the const keyword.
gA global variable (including static members of classes); for example, gApplication,TGame::gPlayingField.
TA class definition (as in TWindow in MacApp).
MFor multiple inheritance classes (or "mix-in" classes).
eEnumerated type (eg eColorConstant).
ecEnumerated type member item (eg ecRed).

Type

Define base types as abbreviations or acronyms of the type's description, or as some other memorable or random sequence of characters, preferably two or three characters long.

If it's truly necessary to refer to the native C types such as word, unsigned-word and long word types, the tags w, u and l are acceptable. Standard base types, derived from Hungarian, are:

bf(flag)A boolean flag. The qualifier indicates the condition under which the value is true, for example bfOpen.
chA 1 byte ASCII character.
szA 'C' type null terminated string.
spA Pascal type string, where the first byte contains the length.
pA pointer. For example, pch is a pointer to a character ((char*) in c).
hA handle - a pointer to a pointer.

Qualifier

The qualifier contains information about the use and purpose of the variable. This is almost pure Hungarian, and the following list is drawn from Simonyi and Heller:
iAn index into an array of elements with the given type.
cSome count of instances of the given type (for example, cch is a count of characters).
dThe numeric difference between two instances of the given type (for example, DX is the integer difference called X, perhaps the width of a rectangle).
Temp (or T)A temporary variable.
SavA temporary variable from which the value will be restored.
PrevA save value that lags behind a current value by one iteration.
CurThe current value in some enumeration.
NextNext value in some enumeration.
Dest, SrcDestination and source, for example used in buffer handling.
NilAn empty, invalid value for some variable type.
1,2Numbers can be used to distinguish between similar variables.
BufA buffer.
MinSmallest legal index. Typically defined to be 0.
MaxThe allocation limit of some stack.
FirstFirst element of some interval.
LastLast element of some interval.
Mnemonic Mnemonics distinguish variables with identical types in a specific context. English words can be used. Because they are almost always used with a type, there is no danger of ambiguity, and because they are not build up like types, their length need not be curtailed to the same extent.

In naming functions, the mnemonic defines the operation of the function. It is possible to define a standard set of function mnemonics, for example "Get" and "Set" in instance access functions (theRect.IXGet() or thePoint.SetIX(10)).

Guidelines

See the sidebar for a brief list of style guidelines to keep handy, compiled from the articles listed in the bibliography and from our experience in-house. Guidelines are just that. They are not written in stone.

I hope this article will provoke debate and thought on the subject. Some kind of style convention is vital-whether it is a home grown "adhocracy" or a strictly imposed formal discipline. Because computer programming remains a literal process, it is still important to say what you mean and mean what you say.

Bibliography

  • "The Hungarian Revolution," Charles Simonyi and Martin Heller, Byte August 1991.
  • "Programmers At Work" interview with Charles Simonyi, Microsoft Press.
  • "Unofficial C++ Style Guide" Goldsmith and Palevich, DEVELOP issue 2.
  • "The Mythical Man Month," F.P. Brooks Jr., N.Carolina, Addison Wesley 1982.
 
AAPL
$524.94
Apple Inc.
+5.93
MSFT
$40.01
Microsoft Corpora
-0.39
GOOG
$536.10
Google Inc.
-20.44

MacTech Search:
Community Search:

Software Updates via MacUpdate

Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty 1.1.1.180...
Download the patch by launching the Starcraft II game and downloading it through the Battle.net connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
MYStuff Pro 2.0.16 - Create inventories...
MYStuff Pro is the most flexible way to create detail-rich inventories for your home or small business. Add items to MYStuff by dragging and dropping existing information, uploading new images, or... Read more
TurboTax 2013.r17.002 - Manage your 2013...
TurboTax guides you through your tax return step by step, does all the calculations, and checks your return for errors and overlooked deductions. It lets you file your return electronically to get... Read more

Latest Forum Discussions

See All

Sparkle Unleashed Review
Sparkle Unleashed Review By Jennifer Allen on April 18th, 2014 Our Rating: :: CLASSY MARBLE FLINGINGUniversal App - Designed for iPhone and iPad It’s a concept we’ve seen before, but Sparkle Unleashed is a solidly enjoyable orb... | Read more »
Tilt to Live 2: Redonkulus Receives its...
Tilt to Live 2: Redonkulus Receives its First Update – Gets New Brimstone Pinball DLC Posted by Rob Rich on April 18th, 2014 [ permalink ] | Read more »
Where's My Water? Featuring XYY (G...
Where's My Water? Featuring XYY 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: iPod Touch 4th Gen, iPhone 3GS or iPad 1 are not compatible with this app. | Read more »
The Amazing Spider-Man 2 (Games)
The Amazing Spider-Man 2 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: *IMPORTANT* The Amazing Spider-Man 2 requires an iPad 2 (or newer), iPhone 4s (or newer), or iPod touch 5th... | Read more »
Living Planet - Tiny Planet Videos and P...
Living Planet - Tiny Planet Videos and Photos 1.0 Device: iOS Universal Category: Photography Price: $.99, Version: 1.0 (iTunes) Description: 50% OFF LAUNCH SPECIAL! BUY NOW BEFORE THE PRICE GOES UP... | Read more »
Livescribe 3 Smartpen Review
Made by: Livescribe Price: $149.99 for Livescribe 3 Hardware/iOS Integration Rating: 4.5 out of 5 stars Usability Rating: 4 out of 5 stars Reuse Value Rating: 4.75 out of 5 stars Build Quality Rating: 4.5 out of 5 stars Overall Rating: 4.44 out of... | Read more »
Unpossible Review
Unpossible Review By Carter Dotson on April 17th, 2014 Our Rating: :: RALPH WIGGUM APPROVESUniversal App - Designed for iPhone and iPad Unpossible is much better than its English!   | Read more »
Hitman GO Review
Hitman GO Review By Carter Dotson on April 17th, 2014 Our Rating: :: GO HITMAN, GO!Universal App - Designed for iPhone and iPad Hitman GO is not the obvious way to do a mobile version of the Hitman series, but it’s an incredibly... | Read more »
Monster High Ghouls and Jewels is a Frea...
Monster High Ghouls and Jewels is a Freaky Fashion-Forward Match-3 Puzzler Posted by Rob Rich on April 17th, 2014 [ permalink ] | Read more »
Dinosaur Train A to Z Review
Dinosaur Train A to Z Review By Amy Solomon on April 17th, 2014 Our Rating: :: DINO DETAILSUniversal App - Designed for iPhone and iPad Dinosaur Train A to Z is an educational app about dinosaurs that includes In-App Purchases... | Read more »

Price Scanner via MacPrices.net

iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more
Save up to $270 with Apple refurbished 13-inc...
The Apple Store has Apple Certified Refurbished October 2013 13″ Retina MacBook Pros available starting at $1099, with models up to $270 off MSRP. Apple’s one-year warranty is standard, and shipping... Read more
Apple now offering refurbished iPad mini with...
The Apple Store has Certified Refurbished 2nd generation iPad minis with Retina Displays now available starting at $339. Apple’s one-year warranty is included with each model, and shipping is free.... Read more
Microsoft Blinks – Drops Microsoft Office 365...
Microsoft has dropped the annual subscription fee for Microsoft Office 365 Personal – which is needed in order to create and edit documents in Microsoft Office for iPad. However, Apple’s iOS and OS X... Read more
New AVG Vault Apps for iOS and Android Help K...
AVG Technologies N.V. an online security company for 177 million active users, has announced the launch of its latest mobile application, AVG Vault. The free app introduces an innovative user... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Manager - Holyoke - Apple I...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Market Leader - Cincinnati...
…challenges of developing individuals, building teams, and affecting growth across Apple Stores. You demonstrate successful leadership ability - focusing on excellence Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.