473,657 Members | 2,504 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Naming convention fit for C++

Hi all,

Disclaimer: before I might trigger your "let's start a holy war!" button,
I'd like to say I'm not intended to; I just post this message to get some
input and not to promote "Yet Another Naming Convention". It's a bit of a
long post, but I've spent the past few days on perfecting this, finally came
to the conclusion that maybe I went a bit overboard with it, almost willing
to just say "the @#$ with it" but I didn't want to let it all go to waste...
Anyway, here it goes:

Up till now, I used a naming convention I borrowed from my last 2 jobs (I
switched jobs together with the team manager). Since I didn't have any
convention before that, I just adopted it and thought nothing about it ever
since, and I also used it for hobby projects at home. It's a form of
shortened and generalized Hungarian Notation, applied the wrong way as well;
"explicit data type = prefix" in stead of "intended data type = prefix". To
give an idea: all numbers have a prefix 'n' (from number), all class
instances an 'o' (from object), possibly resulting in e.g. compiling but not
wrong-looking "nDayOfTheW eek = nCircleRadius" or "nColor =
oBankAccount.Ge tID()" (where GetID returns e.g. an int or so).

But now the times have changed, and I've started making serious programs for
my own company (hurray!). And then a shortcoming in my inherited coding
convention started biting me in the @ss (two distinct usage of the same data
type getting mixed up, causing an infrequent bug that almost slipped my
attention); time to rethink the coding convention.

I read some (well, a lot of) posts, trying to extract some usefull ideas
from out of the usual bickering about coding conventions. What I've come up
with so far is a syntax that has aspects of "True" Hungarian notation and
common SmallTalk conventions (or so I've heard). I think the benefit of it
is that code inspection will catch some bugs compilers won't catch (like in
True Hungarian; one basic type being used for more than one variable, all
with another purpose, and mixing the purposes up). Furthermore it's much
more closer to standard English than Hungarian is, so the names (kind of)
read out like you'd call the thing in plain English. And the downside of
Hungarian (getting to remember all those zillion standard abbreviations, and
then also invent and maintain your own) is also bypassed.

============== Syntax ==============

0) Scope prefixes
m: member scope
g: global scope

1) Modifier prefixes
c: const
h: handle to
p: pointer to
r: reference to
s: set of

2) Typenames
T[<modifiers>]<Type>;
So, typenames can have modifiers embedded into them if needed for
clarification.

3) Subject (helper intermediate stage for Variables and Functions)
[<modifiers>][<Name>]<Type>
Any modifiers embedded in the used type will migrate to the front with the
rest of the modifiers (but keep their relative order).
I'm still not sure whether the <Name> part should be optional...

4) Variables
[<scope>]<Subject>

5) Functions
<Name(Action)>_ <Subject(Return Type)>[_<Name(Clause1) >_<Subject(Clau se1)>[_<Name(Clause2) >_<Subject(Clau se2)>[...]]]
The optional clauses denote extra info on the workings of the function in
terms of the parameters; clause 1 descibes parameter 1, etc. Not all
parameters need to be described (I want to keep overloading to work), but
immutable _intended_ parameter usage will benefit from this I think.

6) 'Procedures' (void functions)
<Name(Action) >[<Name(Clause1)> _<Subject(Claus e1)>[_<Name(Clause2) >_<Subject(Clau se2)>[...]]]

7) Additional rules
Type will be the name of the intended type used, not the exact
implementation.
Abbreviation of names and types is allowed, unless it diminishes the
clarity.

Ok, now that the rules are laid out, lets show some examples of what this
boils down to:

============== Examples ==============
// Date class that manipulates dates, and is compatible with the type
'double'
class TDate {
...
};

// Set of pointers to dates
typedef std::vector<TDa te*> TspDate;

// Date variable
TDate* pStartDate;
double EndDate;

// Member instance of the set of pointers to date;
// keeps a set of references to start dates.
class ... {
TspDate mspStartDate;
TColor mColor; // No explicitly added name; can only have 1 color
};

// Function returning a date
// Declaration:
TDate* Get_pDate_From_ crDataFile(cons t TDataFile& crInputDataFile , TDate
DefaultStartDat e);
// Usage:
double UnknownDate = 0.0;
*ppStartDate = Get_pDate_From_ crDataFile(Temp DataFile, UnknownDate);

// Function performing some action
// The 2nd parameter can be said to be of type "format"
// Declaration:
Print_Date(doub le Date, char* DisplayFormat);
// Usage:
Print_Date(mSta rtDate, "ddmmyyyy") ;
Ok, these examples are good to understand for everyone I think (well, I
hope). The downside I think is that the notation is _quite_ verbose, but
any misinterpretati on is minimalized.

Another downside is that the verbosity can quickly add up when you have
extended types via typedefs; a live example from the code I used to test the
convention:
class ... {
private:
typedef std::map<TStatC acheID, TStatInt*> TspStatCacheID2 StatInt;
TspStatCacheID2 StatInt mspStatCacheID2 StatInt;
}
where before I would have used:
typedef std::map<CStatC acheID, CStatInt*> CID2Int;
CID2Int m_apIntsByID;
In this case the extra abbreviation of the class type isn't harmfull,
because all classes involved have no conversion operators whatsoever (all
misuse will be penalized with a compile error). Using the new convention
doubles the names, which makes code lines scroll off the screen quite
fast... And though I strive for perfection of my code, I'm also lazy enough
not to want to type "mspStatCacheID 2StatInt" every time...

Yet another thing I find at fault with this convention is that, althoug the
name is suffixed with the type, there is no delimiter between them (DataFile
InputDataFile; is that a File for InputData, or a DataFile for Input?). The
underscore is already reserved for use in functions (where I need to
seperate the actions from the subjects), and CamelCase is already at work
within the names and types. If only I could use bold or italics in my code
:(

And a final grudge I have about this new convention is that flag values
(booleans) have no clear type; what about e.g.:
bool Get_Success_Fro mPrint_pDate(TD ate* pDate);
I'd rather just use Print_pDate(... ) ... Or:
bool FailSuccess = !Get_Success_Fr om....()
type returned by the function is "Success", so the variable better have that
type as well (don't want to loosen the usage of the convention; if I allow
so, then what's the use?). I could use a general flag type called "Flag"
(typedef bool TFlag), but that makes the looks-like-English to fail;
TFlag SuccessFlag = Get_Flag_From.. .()
or
TFlag SuccessFlag = Get_SuccessFlag _From...()
which is even more verbose...

In my code I make use of two types of dates; dates in local time and dates
in UTC. Obviously it's not a good idea to mix these without using mapping
functions ("ToLocal()" , "ToUTC()"). In my old notation, both types would
cause a prefix letter 'd' (from 'date') to be used, but now I just 'invent'
the type TDateL and TDateU (both typedefs to a class TDate from a library I
use). This still won't cause the compiler to catch any semantic errors, but
any code review will.

I did try a better solution: generating 2 derived classes from TDate. But
that caused a lot of headaches as well; I either have to recreate all
constructors and assignment operators (and TDate has a lot of those :) );
this task I can alleviate by adding a templatized constructor like
template<typena me TParam>
TDateU(const TParam& crParam): TDate(crParam) {};
but that still leaves implicit conversions like e.g.
TDateU => double => TDateL, or
TDateU => SYSTEMTIME => TDateL
and I _need_ those conversions (I do a lot of arithmetic with and
conversions of dates).

And so the bottom line: what do you think of it? Any ideas about the
verbosity?

Thanks for reading this far ;)
Kind regards,
Carl
Nov 22 '05 #1
0 1739

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

27
6696
by: Derek | last post by:
The company where I work uses a naming convention that I have never used before. They use mixed-case letters for public member functions, but lower-case with underscores for the rest, like this: class Foo { public: void somePublicMemberFunction(); protected:
7
2471
by: cmiddlebrook | last post by:
Hi there, I keep finding myself getting inconsistent with naming conventions for things like member variables, class names etc and I just want to find something that suits me and stick to it. I am wondering if there are any naming conventions around that are deemed suitable by the general C++ community. I have googled around and I can't find much - mostly long lists of hungarian-like prefixes which is not really what I'm after.
4
7144
by: Mark Broadbent | last post by:
stupid question time again to most of you experts but this is something that continually bothers me. I am trying to get into the habit of naming variables and controls in an assembly as per convensions. The thing is that Ive never really get the full reference to check against. Ive seen a couple of articles, but there always seems to be a bit missing. I also always seem to run into conflicting convensions both in code samples themselves...
14
3129
by: 42 | last post by:
Hi, Stupid question: I keep bumping into the desire to create classes and properties with the same name and the current favored naming conventions aren't automatically differentiating them... (both are "Pascal Case" with no leading or trailing qualifiers). For example... I'll be modelling something, e.g. a computer, and I'll
10
17768
by: jjkboswell | last post by:
I'm trying to pin down a good naming convention for the 3 things required to implement an event. You need: 1) a delegate 2) an event 3) an event handler Below is my understanding of a naming convention based on the Windows Forms events. Can someone let me know if this convention is standard,
11
4995
by: MP | last post by:
Hi, Coming from a vb6 background I am accustomed to prefixing variable names to indicate their usage. Now just beginning to try to learn database stuff I've been lurking here and working on my first database design. I was noticing that I never see peoples posts here containing prefixed object identifiers If I had a table to contain job records I thought I'd name it tblJobs
6
4062
by: dm1608 | last post by:
I'm relatively new to ASP.NET 2.0 and am struggling with trying to find the best naming convention for the BAL and DAL objects within my database. Does anyone have any recommendations or best practices for naming my objects? I currently have all my type classses simply called "JobSummaryClass" or "JobDetailsClass". These classes simply contain the public properties and the get/set functions for the object. Is this an appropriate naming...
114
7823
by: Jonathan Wood | last post by:
I was just wondering what naming convention most of you use for class variables. Underscore, "m_" prefix, camel case, capitalized, etc? Has one style emerged as the most popular? Thanks for any comments. --
35
12175
by: Smithers | last post by:
Is it common practise to begin the name of form classes with "frm" (e.g., frmOneForm, frmAnotherForm). Or is that generally considered an outdated convention? If not "frm" what is a common or recommended practise? Thanks.
0
8305
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8823
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8726
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8603
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7320
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4151
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1944
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.