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
$99.02
Apple Inc.
+1.35
MSFT
$43.97
Microsoft Corpora
-0.53
GOOG
$590.60
Google Inc.
+1.58

MacTech Search:
Community Search:

Software Updates via MacUpdate

OS X Yosemite Wallpaper 1.0 - Desktop im...
OS X Yosemite Wallpaper is the gorgeous new background image for Apple's upcoming OS X 10.10 Yosemite. This wallpaper is available for all screen resolutions with a source file that measures 5,418... Read more
Acorn 4.4 - Bitmap image editor. (Demo)
Acorn is a new image editor built with one goal in mind - simplicity. Fast, easy, and fluid, Acorn provides the options you'll need without any overhead. Acorn feels right, and won't drain your bank... Read more
Bartender 1.2.20 - Organize your menu ba...
Bartender lets you organize your menu bar apps. Features: Lets you tidy your menu bar apps how you want. See your menu bar apps when you want. Hide the apps you need to run, but do not need to... Read more
TotalFinder 1.6.2 - Adds tabs, hotkeys,...
TotalFinder is a universally acclaimed navigational companion for your Mac. Enhance your Mac's Finder with features so smart and convenient, you won't believe you ever lived without them. Tab-based... Read more
Vienna 3.0.0 RC 2 :be5265e: - RSS and At...
Vienna is a freeware and Open-Source RSS/Atom newsreader with article storage and management via a SQLite database, written in Objective-C and Cocoa, for the OS X operating system. It provides... Read more
VLC Media Player 2.1.5 - Popular multime...
VLC Media Player is a highly portable multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, MP3, OGG, ...) as well as DVDs, VCDs, and various streaming protocols. It... Read more
Default Folder X 4.6.7 - Enhances Open a...
Default Folder X attaches a toolbar to the right side of the Open and Save dialogs in any OS X-native application. The toolbar gives you fast access to various folders and commands. You just click... Read more
TinkerTool 5.3 - Expanded preference set...
TinkerTool is an application that gives you access to additional preference settings Apple has built into Mac OS X. This allows to activate hidden features in the operating system and in some of the... Read more
Audio Hijack Pro 2.11.0 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
Intermission 1.1.1 - Pause and rewind li...
Intermission allows you to pause and rewind live audio from any application on your Mac. Intermission will buffer up to 3 hours of audio, allowing users to skip through any assortment of audio... Read more

Latest Forum Discussions

See All

Traps n’ Gemstones Review
Traps n’ Gemstones Review By Campbell Bird on July 28th, 2014 Our Rating: :: CASTLEVANIA JONESUniversal App - Designed for iPhone and iPad Fight mummies, dig tunnels, and ride a runaway minecart to discover ancient secrets in this... | Read more »
The Phantom PI Mission Apparition Review
The Phantom PI Mission Apparition Review By Jordan Minor on July 28th, 2014 Our Rating: :: GHOSTS BUSTEDUniversal App - Designed for iPhone and iPad The Phantom PI is an exceedingly clever and well-crafted adventure game.   | Read more »
More Stubies Are Coming Your Way in a Ne...
More Stubies Are Coming Your Way in a New Update Posted by Jessica Fisher on July 28th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
The Great Prank War Review
The Great Prank War Review By Nadia Oxford on July 28th, 2014 Our Rating: :: PRANKING IS SERIOUS BUSINESSUniversal App - Designed for iPhone and iPad Though short, The Great Prank War offers an interesting and fun mix of action and... | Read more »
Marvel Contest of Champions Announced at...
Marvel Contest of Champions Announced at Comic-Con Posted by Jennifer Allen on July 28th, 2014 [ permalink ] Announced over the weekend at San Diego Comic-Con was the fairly exciting looking Marvel Contest of Champions. | Read more »
Teenage Mutant Ninja Turtles Review
Teenage Mutant Ninja Turtles Review By Jennifer Allen on July 28th, 2014 Our Rating: :: DULL SWIPINGUniversal App - Designed for iPhone and iPad The pizza power is weak when it comes to this Teenage Mutant Ninja Turtles game.   | Read more »
Exploration Focused Puzzle Game Beatbudd...
Exploration Focused Puzzle Game Beatbuddy Set to Make Transition from PC to iOS this September Posted by Jennifer Allen on July 28th, 2014 [ permalink ] | Read more »
PlanetHD
PlanetHD By Nadia Oxford on July 28th, 2014 Our Rating: :: SPACE MADNESSUniversal App - Designed for iPhone and iPad PlanetHD will keep players busy for a while, though its unpredictable physics are a handful to deal with.   | Read more »
This Week at 148Apps: July 21-25, 2014
Another Week of Expert App Reviews   At 148Apps, we help you sort through the great ocean of apps to find the ones we think you’ll like and the ones you’ll need. Our top picks become Editor’s Choice, our stamp of approval for apps with that little... | Read more »
Reddme for iPhone - The Reddit Client (...
Reddme for iPhone - The Reddit Client 1.0 Device: iOS iPhone Category: News Price: $.99, Version: 1.0 (iTunes) Description: Reddme for iPhone is an iOS 7-optimized Reddit client that offers a refreshing new way to experience Reddit... | Read more »

Price Scanner via MacPrices.net

iOS 8 and OS X 10.10 To Support DuckDuckGo As...
Writing for Quartz, Dan Frommer reports that Apple’s forthcoming iOS 8 and OS X 10.10 operating systems version updates will allow users to select DuckDuckGo as their default search engine. He notes... Read more
U.K. Hospital Using iPods and iPads To Record...
British news journal GazetteLive’s. Ian McNeal notes that the old “an apple a day keeps the doctor away” proverb is being turned on its head at http://southtees.nhs.uk/hospitals/james-cook/ James... Read more
13-inch 2.5GHz MacBook Pro on sale for $1099,...
Best Buy has the 13″ 2.5GHz MacBook Pro available for $1099.99 on their online store. Choose free shipping or free instant local store pickup (if available). Their price is $100 off MSRP. Price is... Read more
Roundup of Apple refurbished MacBook Pros, th...
The Apple Store has Apple Certified Refurbished 13″ and 15″ MacBook Pros available for up to $400 off the cost of new models. Apple’s one-year warranty is standard, and shipping is free. Their prices... Read more
Record Mac Shipments In Q2/14 Confound Analys...
A Seeking Alpha Trefis commentary notes that Apple’s fiscal Q3 2014 results released July 22, beat market predictions on earnings, although revenues were slightly lower than anticipated. Apple’s Mac’... Read more
Intel To Launch Core M Silicon For Use In Not...
Digitimes’ Monica Chen and Joseph Tsai, report that Intel will launch 14nm-based Core M series processors specifically for use in fanless notebook/tablet 2-in-1 models in Q4 2014, with many models to... Read more
Apple’s 2014 Back to School promotion: $100 g...
 Apple’s 2014 Back to School promotion includes a free $100 App Store Gift Card with the purchase of any new Mac (Mac mini excluded), or a $50 Gift Card with the purchase of an iPad or iPhone,... Read more
iMacs on sale for $150 off MSRP, $250 off for...
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
Mac minis on sale for $100 off MSRP, starting...
Best Buy has Mac minis on sale for $100 off MSRP. Choose free shipping or free instant local store pickup. Prices are for online orders only, in-store prices may vary: 2.5GHz Mac mini: $499.99 2.3GHz... Read more
Global Tablet Market Grows 11% in Q2/14 Notwi...
Worldwide tablet sales grew 11.0 percent year over year in the second quarter of 2014, with shipments reaching 49.3 million units according to preliminary data from the International Data Corporation... Read more

Jobs Board

Sr Software Lead Engineer, *Apple* Online S...
Sr Software Lead Engineer, Apple Online Store Publishing Systems Keywords: Company: Apple Job Code: E3PCAK8MgYYkw Location (City or ZIP): Santa Clara Status: Full 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
Sr. Product Leader, *Apple* Store Apps - Ap...
**Job Summary** Imagine what you could do here. At Apple , great ideas have a way of becoming great products, services, and customer experiences very quickly. Bring 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* 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.