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
$100.96
Apple Inc.
-0.83
MSFT
$47.52
Microsoft Corpora
+0.84
GOOG
$596.08
Google Inc.
+6.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

Airfoil 4.8.9 - Send audio from any app...
Airfoil allows you to send any audio to AirPort Express units, Apple TVs, and even other Macs and PCs, all in sync! It's your audio - everywhere. With Airfoil you can take audio from any... Read more
WhatRoute 1.13.0 - Geographically trace...
WhatRoute is designed to find the names of all the routers an IP packet passes through on its way from your Mac to a destination host. It also measures the round-trip time from your Mac to the... Read more
Chromium 37.0.2062.122 - Fast and stable...
Chromium is an open-source browser project that aims to build a safer, faster, and more stable way for all Internet users to experience the web. FreeSMUG-Free OpenSource Mac User Group build is... Read more
Attachment Tamer 3.1.14b9 - Take control...
Attachment Tamer gives you control over attachment handling in Apple Mail. It fixes the most annoying Apple Mail flaws, ensures compatibility with other email software, and allows you to set up how... Read more
Duplicate Annihilator 5.0 - Find and del...
Duplicate Annihilator takes on the time-consuming task of comparing the images in your iPhoto library using effective algorithms to make sure that no duplicate escapes. Duplicate Annihilator detects... Read more
jAlbum Pro 12.2 - Organize your digital...
jAlbum Pro has all the features you love in jAlbum, but comes with a commercial license. With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code!... Read more
jAlbum 12.2 - Create custom photo galler...
With jAlbum, you can create gorgeous custom photo galleries for the Web without writing a line of code! Beginner-friendly, with pro results Simply drag and drop photos into groups, choose a design... Read more
Quicken 2015 2.0.4 - Complete personal f...
Quicken 2015 helps you manage all your personal finances in one place, so you can see where you're spending and where you can save. Quicken automatically categorizes your financial transactions,... Read more
iMazing 1.0 - Complete iOS device manage...
iMazing (formerly DiskAid) is the ultimate iOS device manager with capabilities far beyond what iTunes offers. With iMazing and your iOS device (iPhone, iPad, or iPod), you can: Copy music to and... Read more
Xcode 6.0.1 - Integrated development env...
Apple Xcode is Apple Computer's integrated development environment (IDE) for OS X. The full Xcode package is free to ADC members and includes all the tools you need to create, debug, and optimize... Read more

Latest Forum Discussions

See All

View Source – HTML, JavaScript and CSS...
View Source – HTML, JavaScript and CSS 1.0 Device: iOS Universal Category: Utilities Price: $.99, Version: 1.0 (iTunes) Description: View Source is an app plus an iOS 8 Safari extension that makes it easy to do one key web developer... | Read more »
Avenged Sevenfold’s Hail To The King: De...
Avenged Sevenfold’s Hail To The King: Deathbat is Coming to iOS on October 16th Posted by Jessica Fisher on September 19th, 2014 [ permalink ] Just in time for Halloween, on October 16 Avenged Sevenfold will be launching | Read more »
Talisman Has Gone Universal – Can Now be...
Talisman Has Gone Universal – Can Now be Played on the iPhone Posted by Jessica Fisher on September 19th, 2014 [ permalink ] | Read more »
Tap Army Review
Tap Army Review By Jennifer Allen on September 19th, 2014 Our Rating: :: SHOOT EM ALLUniversal App - Designed for iPhone and iPad Mindless but fun, Tap Army is a lane-based shooter that should help you relieve some stress.   | Read more »
Monsters! Volcanoes! Loot! Epic Island f...
Monsters! Volcanoes! Loot! | Read more »
Plunder Pirates: Tips, Tricks, Strategie...
Ahoy There, Seadogs: Interested in knowing our thoughts on all this plundering and pirating? Check out our Plunder Pirates Review! Have you just downloaded the rather enjoyable pirate-em-up Plunder Pirates and are in need of some assistance? Never... | Read more »
Goat Simulator Review
Goat Simulator Review By Lee Hamlet on September 19th, 2014 Our Rating: :: THE GRUFFEST OF BILLY GOATSUniversal App - Designed for iPhone and iPad Unleash chaos as a grumpy goat in this humorous but short-lived casual game.   | Read more »
A New and Improved Wunderlist is Here fo...
A New and Improved Wunderlist is Here for iOS 8 Posted by Jessica Fisher on September 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Evernote Update for iOS 8 Adds Web Clipp...
Evernote Update for iOS 8 Adds Web Clipping, Quick Notes, and More Posted by Ellis Spice on September 19th, 2014 [ permalink ] | Read more »
Apple Names Ultimate Productivity Bundl...
Apple Names Ultimate Productivity Bundle by Readdle as the Essential Bundle on the App Store Posted by Jessica Fisher on September 19th, 2014 [ permalink | Read more »

Price Scanner via MacPrices.net

Updated Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
Mac Pros available for up to $260 off MSRP
Adorama has Mac Pros on sale for up to $260 off MSRP. Shipping is free, and Adorama charges sales tax in NY & NJ only: - 4-core Mac Pro: $2839.99, $160 off MSRP - 6-core Mac Pro: $3739.99, $260... Read more
13-inch 2.6GHz/256GB Retina MacBook Pros avai...
B&H Photo has the 13″ 2.6GHz/256GB Retina MacBook Pro on sale for $1379 including free shipping plus NY sales tax only. Their price is $120 off MSRP. Read more
Previous-generation 15-inch 2.0GHz Retina Mac...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
21″ 2.7GHz iMac available for $1179, save $12...
Adorama has 21″ 2.7GHz Hawell iMacs on sale for $1179.99 including free shipping. Their price is $120 off MSRP. NY and NJ sales tax only. Read more
iOS 8 Adoption Rate Slower than iOS 7, 6, Hit...
Apple began pushing out iOS 8 updates to eligible devices around 1pm ET on September 17, 2014. However, unlike with iOS 7, which boasted a wide variety of differences from its predecessor iOS 6, in... Read more
LIkely Final Definitive OS X 10.9.5 Mavericks...
Apple has released what will almost certainly be the last incremental version number update of OS X 10.9 Mavericks (save for futire security updates) before OS X 10.10 Yosemite is released next month... Read more
Fingerprints, Apple Pay and Identity Theft Wa...
On Sep 9th, CEO Tim Cook unveiled Apple Pay, along with the new iPhone 6 and iWatch. Apple Pay is a newly developed technology that utilizes a near field communication (NFC) to enable customer... Read more
Amazon Introduces Two All-New Kindles
Amazon on Thursday introduced the 7th generation of its Kindle dedicated e-reader device: Kindle Voyage, its top-of-the-line e-reader, and the new $79 Kindle, with a 20% faster processor, twice the... Read more
Save up to $300 on the price of a new Mac wit...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more

Jobs Board

*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.