32

Symbian C++ Coding Standards Booklet (English)

  • Upload
    symbian

  • View
    161

  • Download
    5

Embed Size (px)

DESCRIPTION

This booklet on Coding Standards is part of "the Essential Symbian OS series". It was formerly hosted on Symbian Developer Network.While the content of the booklet is largely still relevant, the evolving version is here: http://developer.symbian.org/wiki/index.php/Coding_Standards_Quick_Start

Citation preview

Page 1: Symbian C++ Coding Standards Booklet (English)
Page 2: Symbian C++ Coding Standards Booklet (English)

Symbian Signed, developed by Symbian inpartnership with its licensees, network operatorsand developers, promotes best practice to test andsign applications for Symbian smartphones.

Based on developer feedback, the Symbian Signedprocesses have been improved to make signingfaster, easier and cheaper for developers drivinggrowth in the number of Symbian applications.

• Open Signed - provides a free offline signingprocess using Developer Certificates allowing anapplication to be installed and tested on up to1000 devices controlled by declared IMEIs (uniquephone identification numbers).

• Express Signed - an entirely new process to allowsoftware developers with Publisher IDs toinstantly sign all applications that do not requireaccess to the more sensitive device functions,allowing faster time-to-market. Developers cannow sign applications on Expressed Signed for aslittle as US $20.

• Certified Signed - for those applications thatrequire access to restricted system capabilitiesand/or where independent testing is required.

For more information visit www.symbiansigned.com

Page 3: Symbian C++ Coding Standards Booklet (English)

from

Page 4: Symbian C++ Coding Standards Booklet (English)

Coding Standardspart of the Essential Symbian OS series

1st edition: 02/08

Published by:Symbian Software Limited 2-6 Boundary RowSouthwarkLondon SE1 8HPUKwww.symbian.com

Trademarks, copyright, disclaimer‘Symbian’, ‘Symbian OS’ and other associated Symbian marks are all trademarks of Symbian Software Ltd. Symbian acknowledges the trademarkrights of all third parties referred to in this material. © Copyright SymbianSoftware Ltd. 2008. All rights reserved. No part of this material may be reproduced without the express written permission of Symbian Software Ltd.Symbian Software Ltd. makes no warranty or guarantee about the suitabilityor accuracy of the information contained in this document. The informationcontained in this document is for general information purposes only andshould not be used or relied upon for any other purpose whatsoever.

AcknowledgementsThanks to all the highly skilled and experienced software engineerswho have shared their tips and best practice over the years. Manyof the tips in this booklet are drawn from their collective wisdom.

Compiled by:Jo Stichbury

Managing Editor:Ashlee Godwin

Reviewed by:Thomas SutcliffeMark ShackmanHamish Willee

Page 5: Symbian C++ Coding Standards Booklet (English)

Contents

How to use this booklet ..................................................1

The fundamentals ............................................................3

Prefixes ..........................................................................3

Suffixes ..........................................................................5

Underscores ..................................................................6

Capitalization ................................................................6

Header File Guidelines......................................................7

Class and Function Design ..............................................8

Exported Functions ........................................................10

Code Style ......................................................................11

Construction ....................................................................14

Destruction......................................................................14

Exception Handling and Memory Management ..............16

Defensive Programming ..................................................17

Additional Rules ..............................................................18

Further Reading ..............................................................19

References ......................................................................20

Developer Resources ......................................................21

Page 6: Symbian C++ Coding Standards Booklet (English)

How to use this booklet

Not everyone chooses to follow coding standards explicitly,but most developers have a set of rules that they apply totheir code, based on their experience and understanding ofC++. When developers work together, they tend to shareknowledge and best practices, gained from a variety ofsources. This booklet, Coding Standards, is here to helpyou and your team define the standards you apply to thecode you release together. It comprises a set of guidelinesthat you can use to assess the quality of your SymbianC++ code.

By reading and adopting these standards as you write yourcode, you have the basics of consistent and good qualitySymbian C++ in place. The booklet can also be used asinput to any type of code review, when given to eachperson who reviews code, as a way of ensuring thateveryone uses the same assessment criteria.

The guidelines specified here are taken from a broader setof C++ coding standards used by Symbian’s owndevelopers, and those that deliver code to Symbian. Thestandards arise from the many years’ worth of experienceof a number of Symbian’s software engineers, and reflecttheir wisdom and understanding of working in C++ onSymbian OS.

Some of Symbian’s standards do not apply to externaldevelopers so we have removed them, and listed only

1

Page 7: Symbian C++ Coding Standards Booklet (English)

those which make sense to a wide set of developers.What is left should apply equally well to developerswriting code within Symbian or one of its licensees, thosewithin a large development organization writing C++ to beincluded on a Symbian smartphone, or to any SymbianC++ developer writing an aftermarket application,commercial or shareware.

Apply the standards judiciously. There may be exceptionalcases where some of the guidelines do not apply. Whenwriting code that doesn’t seem to fit the standards, thinkand consider whether it should. If you and yourcolleagues decide that you’ve found a case where theguideline does not apply, comment it in the code.

You may have additional standards such as specificlayout requirements, commenting or naming conventions.We’ve not listed any stylistic guidelines, beyond statingthe standard Symbian OS C++ naming conventions,because we believe the layout of your code is for youand your team to define. There are some empty slots atthe end of the booklet where you can add your ownguidelines and preferences.

To allow this booklet to be used as a checklist during acode review, and for reasons of space, we have statedeach guideline in this booklet but have not provided adetailed explanation. You can find more discussion of theguidelines on the Symbian Developer Network wiki atdeveloper.symbian.com/coding_standards_wikipage.

2

Page 8: Symbian C++ Coding Standards Booklet (English)

The fundamentals

1. Compile with no warnings. Set your compiler to usethe highest warning level and compile your codecleanly so it emits no warnings. If you do getwarnings, make sure you understand why and thenalter your code to remove them, even if the codeappears to run correctly despite generating awarning.

2. Follow the Symbian OS naming conventions. If allmembers of a team follow the same namingconventions in their code, it can be shared andmaintained more easily, because it is immediatelyunderstandable. This also applies to code that hasbeen created by a completely different team, such asa utility library or the SDKs for working on SymbianOS itself. Symbian and its licensees use a specificset of rules when naming classes, variable andfunction names, so that those using the developmentkits can easily understand how to use the APIs andexample code provided.

Prefixes

Member variables are prefixed with a lowercase ‘i’, whichstands for ‘instance’. For example:

3

Page 9: Symbian C++ Coding Standards Booklet (English)

TInt iCount;

CBackground* iBitmap;

Parameters are prefixed with a lowercase ‘a’, whichstands for ‘argument’. We do not use ‘an’ for argumentsthat start with a vowel. For example:

void ExampleFunction(TBool aExampleBool,

const TDesC& aName);

(Note: TBool aExampleBool rather than TBoolanExampleBool.)

Local variables have no prefix. For example:

TInt localVariable;

CMyClass* ptr = NULL;

Class names should be prefixed with the letterappropriate to their Symbian OS type, usually ‘C’, ‘R’, ‘T’,or ‘M’, except where they consist only of static memberfunctions. (Please consult a book in the Symbian Pressseries or the Symbian Developer Library for moreinformation about the characteristics of each of theSymbian OS types). For example:

class CActive;

class TParse;

class RFs;

class MCallback;

4

Page 10: Symbian C++ Coding Standards Booklet (English)

Constants are prefixed with ‘K’. For example:

const TInt KMaxFilenameLength = 256;

#define KMaxFilenameLength 256

Enumerations are simple types, and so are prefixed with‘T’. Enumeration members are prefixed with ‘E’. Forexample:

enum TWeekday {EMonday, ETuesday, ...};

Member functions that set a member variable to a valueare named SetXxx(). Member functions that retrieve thevalue of a member variable as a reference parameter arenamed GetXxx(). Those that return the value of amember variable are simply named Xxx(). For example:

void SetSpeed(TInt aSpeed);

void GetSpeed(TInt& aSpeed) const;

TInt Speed() const;

Suffixes

A trailing ‘L’ on a function name indicates that thefunction may leave. For example:

void AllocL();

5

Page 11: Symbian C++ Coding Standards Booklet (English)

Conversely, if you name a function without a trailing ‘L’you are effectively guaranteeing to all that call it that itwill never leave.

A trailing ‘C’ on a function name indicates that thefunction returns a pointer that has been pushed on tothe cleanup stack. For example:

static CCylon* NewLC();

A trailing ‘D’ on a function name means that it will resultin the deletion of the object referred to by the function.For example:

TInt ExecuteLD(TInt aResourceId);

Underscores

Underscores are avoided in names except in macros(__ASSERT_DEBUG) or resource files (MENU_ITEM).

Capitalization

The first letter of class names is capitalized. For example:

class TColor;

6

Page 12: Symbian C++ Coding Standards Booklet (English)

The words making up variable, class, or function namesare adjoining, with the first letter of each wordcapitalized. Classes and functions have their initial lettercapitalized while, in contrast, function parameters, local,global, and member variables have a lowercase firstletter.

Apart from the first letter of each word (whereappropriate), the rest of each word is given in lowercase,including acronyms. For example:

void CalculateScore(TInt aCorrectAnswers,

TInt aQuestionsAnswered);

class CActiveScheduler;

TInt localVariable;

CShape* iShape;

class CBbc;// Acronyms are not usually

// written in upper case

Macros are specified in capital letters only, usingunderscores to separate individual words.

Header File Guidelines

3. A header file should be ‘self-sufficient’. It shouldcompile on its own, and include any headers that itscontents depend upon. Code that includes theheader should not also have to include others inorder to compile.

7

Page 13: Symbian C++ Coding Standards Booklet (English)

4. A header file should not include more headers thanstrictly necessary. Where appropriate, prefer the useof forward references to reduce the number ofinclusions.

5. Include guards should be used to protect againstmultiple inclusions of headers. For example:

#ifndef GAME_ENGINE_H__

#define GAME_ENGINE_H__

... // Header file code goes here

#endif // GAME_ENGINE_H__

Class and Function Design

6. M classes should be used to specify the interfaceonly, not the implementation, and should generallycontain only pure virtual functions.

7. Multiple inheritance should be used only throughinterfaces defined by M classes. Inherit from oneCBase-derived class and one or more M-classes (theCBase-derived class should appear first in theinheritance list to ensure that destruction by thecleanup stack occurs correctly).

8. Private inheritance should be avoided except in rarecases. Prefer to use composition instead.

8

Page 14: Symbian C++ Coding Standards Booklet (English)

9. Enumerations should be scoped within the class ornamespace to which they are relevant, and shouldnot be global, unless they are required to be, toavoid polluting the global namespace.

10. In class design, overloaded functions should be usedin preference to default parameters.

11. Virtual functions should not be inlined (with theexception of a virtual inline destructor).

12. The inline keyword should be specified explicitlyfor those functions that should be inlined.

13. In functions, reference parameters should generallybe used in preference to pointers, except whereownership is transferred or if it is valid for theparameter to be NULL. In those cases, a pointer mustbe used.

14. In functions, the const specifier should always beused for parameters and return values if the data isnot intended to be modified.

15. In functions, pass by value should only be used forbasic data types or Symbian OS T class objects thatare small (<8 bytes). Pass by reference should beused for larger objects (≥8 bytes).

9

Page 15: Symbian C++ Coding Standards Booklet (English)

Exported Functions

16. Every function whose header file declaration istagged with IMPORT_C must have its implementationtagged with EXPORT_C.

17. Data should not be exported, but a function providedto modify it (a Set() method) or to return it byreference so it can be modified, if this is appropriate.

18. Private functions should only be exported if:

(i) they are accessed by public inline members

(ii) they are virtual and the class is intended to bederived from in code which is not part of theexporting module.

19. Public or protected functions should not be exportedif:

(i) they are not designed for use outside the library

(ii) they are pure virtual functions.

20. Inline functions should never be exported regardlessof whether they are public, protected or private.

10

Page 16: Symbian C++ Coding Standards Booklet (English)

Code Style

21. For efficiency, when initializing member variables in aconstructor, the use of member initialization listsshould be preferred over assignment statements.

22. The member data of a C class does not requireexplicit initialization to zero.

23. When testing Booleans, do not use explicitcomparison. You should use if(iComplete) insteadof if(iComplete==ETrue).

24. When testing pointer values for NULL, it isunnecessary to use explicit comparison, and youshould prefer to use if(ptr) over if(ptr!=NULL),unless writing the comparison in full clarifies theintent of the code.

25. Explicit comparison should be used when testingintegers: use if(aLength!=0) rather thanif(aLength).

26. To avoid scope bloat, automatic variables should notbe declared until required, and should be declared asclose as possible to their point of use.

27. Stack use should be minimized as much as ispossible, for example, use the heap to store largedata structures instead of the stack and take care

11

Page 17: Symbian C++ Coding Standards Booklet (English)

when declaring larger stack-based variables withinloops or recursive functions. Use of the TFileNameand TParse classes is a common cause of stackconsumption, because objects of both types are over512 bytes in size (remember that the default stacksize is only 8KB).

28. Hard-coded ‘magic’ numbers should be avoided.Constants or enumerations should be preferredinstead.

29. The concrete types defined in e32def.h should beused in lieu of the language-defined basic types. Forexample, TInt should be used instead of int.

30. Symbian OS descriptor classes should be used inpreference to native strings and memory buffers oralternative, hand-crafted string classes.

31. The _L macro for literal descriptors should not beused except where it is convenient to do so in testcode. Prefer to use the _LIT macro for literaldescriptors.

32. When using descriptors as function parameters, thebase classes (TDes and TDesC) should be used, andshould be passed by reference.

12

Page 18: Symbian C++ Coding Standards Booklet (English)

33. The Symbian OS date and time classes (such asTDateTime and TTime) should be used instead ofhand-crafted alternatives.

34. In switch statements, the use of fall-through in acase statement should be commented to convey theintent. A switch statement should also alwayscontain a default statement, even if this doesnothing but assert that it is never reached.

35. C++ style casts (for example,static_cast<type>(expression)) should be usedin preference to C style casts. The Symbian OSmacros for the C++ cast operators (for example,STATIC_CAST(type, expression)) should not beused, because they are deprecated.

36. Code in a loop should terminate for all possibleinputs.

37. Thin templates should be used for templated code,to ensure the smallest possible code size while stillgaining the benefits of C++ templates.

38. The use of writable global data should be avoided,where possible, in DLLs.

13

Page 19: Symbian C++ Coding Standards Booklet (English)

Construction

39. The code inside a C++ constructor should not leave.

40. Construction and initialization code that is non-trivialand could fail should be implemented in the secondphase of a two-phase constructor, typically in aConstructL() method.

41. Where two-phase construction is used, one or morepublic static factory functions (typically called NewL()and NewLC()) should be provided for objectconstruction. The construction methods themselvesshould be private or protected.

Destruction

42. When de-referencing a pointer in a destructor, thevalidity of the pointer should first be checked in caseit has not been initialized or it has already beendestroyed by another destructor in the inheritancehierarchy.

43. It is inefficient and unnecessary to set pointers toNULL in a destructor, unless it is likely to be de-referenced elsewhere during destruction, for example,in the destructor of a superclass.

14

Page 20: Symbian C++ Coding Standards Booklet (English)

44. Pointers that are deleted outside of a destructor thatcan later be accessed (for example, member variablepointers) should be set to NULL or immediately re-assigned.

45. Resource handles and heap-based member datashould be cleaned up in a destructor if they areowned by a class.

46. A destructor should not be able to leave or to throwany type of C++ exception.

47. A TRAP may be used within a destructor of a classstored on the heap, but it is not safe to use a TRAPwithin any destructor that may be called as the stackunwinds.

48. If an object is being deleted, it should not be on thecleanup stack.

49. If an object has been allocated by a call to new, itshould be de-allocated by calling delete <object>.Likewise, a C++ array allocated using new [] shouldbe de-allocated by calling delete [] <object>. Forallocations made by calling User::Alloc(), de-allocation should be made by calling User::Free().

15

Page 21: Symbian C++ Coding Standards Booklet (English)

Exception Handling and MemoryManagement

50. When memory is allocated on the heap, to determinewhether the allocation succeeded or failed, either theleaving overload of operator new should be used(new(ELeave)) , or the pointer returned from the callto allocate the memory should be checked againstNULL.

51. The cleanup stack should be used to avoidorphaning of memory or resources in the event of aleave.

52. An object should not be simultaneously owned byanother object and on the cleanup stack. This meansthat class member data should never be placed onthe cleanup stack if it is also destroyed in the classdestructor, as is usually the case.

53. Functions with a ‘C’ suffix on their name (e.g.,NewLC()) automatically put a pointer to the object(s)they allocate on the cleanup stack. Therefore, thoseobjects should not also be pushed onto the cleanupstack explicitly or they will be present twice.

54. When calling code that can throw a C++ exception,catch everything and convert the exceptions toleaves. TRAP and TRAPD will panic if they receive aC++ exception which was not one raised by aSymbian leave (i.e., of type XLeaveException).

16

Page 22: Symbian C++ Coding Standards Booklet (English)

Defensive Programming

55. The checking methods of CleanupStack::Pop()and CleanupStack::PopAndDestroy() should beused where possible, to check that PushL() andPop() calls are balanced.

56. Use the __ASSERT_DEBUG assertion macro liberally todetect programming errors. It may sometimes also beappropriate to use __ASSERT_ALWAYS to catchinvalid runtime input.

57. Assertion statements should not perform ‘side effects’(for example, they should not modify the value of avariable).

58. Assertion statements should be explained using acomment in the code to document the assumptionsthey make and render them easier to maintain.

17

Page 23: Symbian C++ Coding Standards Booklet (English)

Additional Rules

59.

60.

61.

62.

63.

64.

65.

18

Page 24: Symbian C++ Coding Standards Booklet (English)

Further reading

For more information about writing C++ on Symbian OSwe recommend the developer titles published by SymbianPress. More information is available atdeveloper.symbian.com/books.

We also recommend C++ Coding Standards: 101 Rules,Guidelines and Best Practices by Herb Sutter and AndreiAlexandrescu (2005). Pearson Education, Inc.

19

Page 25: Symbian C++ Coding Standards Booklet (English)

References

Symbian Developer Network newsletterdeveloper.symbian.com/register

Symbian OS FAQ databasedeveloper.symbian.com/faqs

Symbian Pressdeveloper.symbian.com/books

20

Page 26: Symbian C++ Coding Standards Booklet (English)

Developer Resources

Symbian Developer Networkdeveloper.symbian.com

Symbian Developer Network newsletterdeveloper.symbian.com/register

Forum Nokiaforum.nokia.com

UIQ Developer Communitydeveloper.uiq.com

21

Page 27: Symbian C++ Coding Standards Booklet (English)

New from

This second edition of DevelopingSoftware for Symbian OS helps softwaredevelopers new to Symbian OS tocreate smartphone applications. Theoriginal book has been updated forSymbian OS v9 and now includes a newchapter on application signing andplatform security, and updatesthroughout for Symbian OS v9 andchanges to the developmentenvironment.

This book forms part of theTechnology Series from SymbianPress. It describes the key aspects ofthe mobile games marketplace, withparticular emphasis on creatinggames for smartphones based onSymbian OS v9.x.

Developing Software for Symbian OS, Second Edition

Games on Symbian OS: A Handbook for Mobile Development

Symbian Press: developer.symbian.com/press

Page 28: Symbian C++ Coding Standards Booklet (English)

New from

This book will help you to become aneffective Symbian OS developer, andwill give you a deep understanding ofthe fundamental principles uponwhich Symbian OS is based.

Targeting Symbian OS v9.1 and v9.2,Symbian OS CommunicationsProgramming - Second Edition willintroduce you to the majorcommunications functionality inSymbian OS and demonstrates howto perform common tasks in eacharea.

Symbian OS C++ for Mobile Phones, Volume 3

Symbian OS CommunicationsProgramming, Second Edition

Symbian Press: developer.symbian.com/press

Page 29: Symbian C++ Coding Standards Booklet (English)

Also from

Fully up to date for Symbian OS v9and S60 3rd Edition, S60Programming is an essentialfoundation to developing software forSymbian OS.This practical book is based on theauthors’ experiences in developingand teaching an academic course onSymbian software development.

This book conducts a rapid tour ofthe architecture of Symbian OS andprovides an introduction to the keyideas of object orientation (OO) insoftware, with a detailed explorationof the architecture of Symbian OS.

S60 Programming

The Symbian OS Architecture Sourcebook

Symbian Press: developer.symbian.com/press

Page 30: Symbian C++ Coding Standards Booklet (English)

Also from

For all Symbian C++ developers:

Symbian OS C++ for Mobile Phones – Volume 1by Richard Harrison

Symbian OS C++ for Mobile Phones – Volume 2by Richard Harrison

Symbian OS Explainedby Jo Stichbury

Symbian OS Internalsby Jane Sales

Symbian OS Platform Securityby Craig Heath

Smartphone Operating System Concepts with Symbian OSby Mike Jipping

Accredited Symbian Developer Primerby Jo Stichbury & Mark Jacobs

Page 31: Symbian C++ Coding Standards Booklet (English)

Published Booklets

Coding Tips

Performance Tips

Getting Started

Java ME on Symbian OS

P.I.P.S

Carbide.c ++

Data Sharing Tips

Essential S60 - Developers' Guide

Essential UIQ - Getting Started

Ready for ROM

Translated booklets available in:Chinese Spanish

Japanese Russian

Korean

Also from

Page 32: Symbian C++ Coding Standards Booklet (English)

This booklet is here to help you define the standards you apply to your code. It comprises a set of guidelines that can be used to assess the quality of C++ code written for Symbian smartphones.

developer.symbian.com/books

Coding Standards is a booklet in the EssentialSymbian OS series, designed to provide information in a handy format for developers working on Symbian OS.