Symbian C++ Coding Standards Booklet (english)

  • Uploaded by: Symbian
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Symbian C++ Coding Standards Booklet (english) as PDF for free.

More details

  • Words: 3,571
  • Pages: 32
Symbian Signed, developed by Symbian in partnership with its licensees, network operators and developers, promotes best practice to test and sign applications for Symbian smartphones. Based on developer feedback, the Symbian Signed processes have been improved to make signing faster, easier and cheaper for developers driving growth in the number of Symbian applications. • Open Signed - provides a free offline signing process using Developer Certificates allowing an application to be installed and tested on up to 1000 devices controlled by declared IMEIs (unique phone identification numbers). • Express Signed - an entirely new process to allow software developers with Publisher IDs to instantly sign all applications that do not require access to the more sensitive device functions, allowing faster time-to-market. Developers can now sign applications on Expressed Signed for as little as US $20. • Certified Signed - for those applications that require access to restricted system capabilities and/or where independent testing is required. For more information visit www.symbiansigned.com

from

Coding Standards part of the Essential Symbian OS series 1st edition: 02/08 Published by: Symbian Software Limited 2-6 Boundary Row Southwark London SE1 8HP UK www.symbian.com Trademarks, copyright, disclaimer ‘Symbian’, ‘Symbian OS’ and other associated Symbian marks are all trademarks of Symbian Software Ltd. Symbian acknowledges the trademark rights of all third parties referred to in this material. © Copyright Symbian Software 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 suitability or accuracy of the information contained in this document. The information contained in this document is for general information purposes only and should not be used or relied upon for any other purpose whatsoever.

Compiled by: Jo Stichbury Managing Editor: Ashlee Godwin

Reviewed by: Thomas Sutcliffe Mark Shackman Hamish Willee

Acknowledgements Thanks to all the highly skilled and experienced software engineers who have shared their tips and best practice over the years. Many of the tips in this booklet are drawn from their collective wisdom.

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

1

How to use this booklet Not everyone chooses to follow coding standards explicitly, but most developers have a set of rules that they apply to their code, based on their experience and understanding of C++. When developers work together, they tend to share knowledge and best practices, gained from a variety of sources. This booklet, Coding Standards, is here to help you and your team define the standards you apply to the code you release together. It comprises a set of guidelines that you can use to assess the quality of your Symbian C++ code. By reading and adopting these standards as you write your code, you have the basics of consistent and good quality Symbian C++ in place. The booklet can also be used as input to any type of code review, when given to each person who reviews code, as a way of ensuring that everyone uses the same assessment criteria. The guidelines specified here are taken from a broader set of C++ coding standards used by Symbian’s own developers, and those that deliver code to Symbian. The standards arise from the many years’ worth of experience of a number of Symbian’s software engineers, and reflect their wisdom and understanding of working in C++ on Symbian OS. Some of Symbian’s standards do not apply to external developers so we have removed them, and listed only

2 those which make sense to a wide set of developers. What is left should apply equally well to developers writing code within Symbian or one of its licensees, those within a large development organization writing C++ to be included on a Symbian smartphone, or to any Symbian C++ developer writing an aftermarket application, commercial or shareware. Apply the standards judiciously. There may be exceptional cases where some of the guidelines do not apply. When writing code that doesn’t seem to fit the standards, think and consider whether it should. If you and your colleagues decide that you’ve found a case where the guideline does not apply, comment it in the code. You may have additional standards such as specific layout requirements, commenting or naming conventions. We’ve not listed any stylistic guidelines, beyond stating the standard Symbian OS C++ naming conventions, because we believe the layout of your code is for you and your team to define. There are some empty slots at the end of the booklet where you can add your own guidelines and preferences. To allow this booklet to be used as a checklist during a code review, and for reasons of space, we have stated each guideline in this booklet but have not provided a detailed explanation. You can find more discussion of the guidelines on the Symbian Developer Network wiki at developer.symbian.com/coding_standards_wikipage.

3

The fundamentals 1.

Compile with no warnings. Set your compiler to use the highest warning level and compile your code cleanly so it emits no warnings. If you do get warnings, make sure you understand why and then alter your code to remove them, even if the code appears to run correctly despite generating a warning.

2.

Follow the Symbian OS naming conventions. If all members of a team follow the same naming conventions in their code, it can be shared and maintained more easily, because it is immediately understandable. This also applies to code that has been created by a completely different team, such as a utility library or the SDKs for working on Symbian OS itself. Symbian and its licensees use a specific set of rules when naming classes, variable and function names, so that those using the development kits can easily understand how to use the APIs and example code provided.

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

4 TInt iCount; CBackground* iBitmap;

Parameters are prefixed with a lowercase ‘a’, which stands for ‘argument’. We do not use ‘an’ for arguments that start with a vowel. For example: void ExampleFunction(TBool aExampleBool, const TDesC& aName);

(Note: TBool aExampleBool rather than TBool anExampleBool.) Local variables have no prefix. For example: TInt localVariable; CMyClass* ptr = NULL;

Class names should be prefixed with the letter appropriate to their Symbian OS type, usually ‘C’, ‘R’, ‘T’, or ‘M’, except where they consist only of static member functions. (Please consult a book in the Symbian Press series or the Symbian Developer Library for more information about the characteristics of each of the Symbian OS types). For example: class class class class

CActive; TParse; RFs; MCallback;

5 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’. For example: enum TWeekday {EMonday, ETuesday, ...};

Member functions that set a member variable to a value are named SetXxx(). Member functions that retrieve the value of a member variable as a reference parameter are named GetXxx(). Those that return the value of a member 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 the function may leave. For example: void AllocL();

6 Conversely, if you name a function without a trailing ‘L’ you are effectively guaranteeing to all that call it that it will never leave. A trailing ‘C’ on a function name indicates that the function returns a pointer that has been pushed on to the cleanup stack. For example: static CCylon* NewLC();

A trailing ‘D’ on a function name means that it will result in 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;

7 The words making up variable, class, or function names are adjoining, with the first letter of each word capitalized. Classes and functions have their initial letter capitalized while, in contrast, function parameters, local, global, and member variables have a lowercase first letter. Apart from the first letter of each word (where appropriate), 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, using underscores to separate individual words.

Header File Guidelines 3.

A header file should be ‘self-sufficient’. It should compile on its own, and include any headers that its contents depend upon. Code that includes the header should not also have to include others in order to compile.

8 4.

A header file should not include more headers than strictly necessary. Where appropriate, prefer the use of forward references to reduce the number of inclusions.

5.

Include guards should be used to protect against multiple 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 interface only, not the implementation, and should generally contain only pure virtual functions.

7.

Multiple inheritance should be used only through interfaces defined by M classes. Inherit from one CBase-derived class and one or more M-classes (the CBase-derived class should appear first in the inheritance list to ensure that destruction by the cleanup stack occurs correctly).

8.

Private inheritance should be avoided except in rare cases. Prefer to use composition instead.

9 9.

Enumerations should be scoped within the class or namespace to which they are relevant, and should not be global, unless they are required to be, to avoid polluting the global namespace.

10. In class design, overloaded functions should be used in preference to default parameters. 11. Virtual functions should not be inlined (with the exception of a virtual inline destructor). 12. The inline keyword should be specified explicitly for those functions that should be inlined. 13. In functions, reference parameters should generally be used in preference to pointers, except where ownership is transferred or if it is valid for the parameter to be NULL. In those cases, a pointer must be used. 14. In functions, the const specifier should always be used for parameters and return values if the data is not intended to be modified. 15. In functions, pass by value should only be used for basic data types or Symbian OS T class objects that are small (<8 bytes). Pass by reference should be used for larger objects (≥8 bytes).

10

Exported Functions 16. Every function whose header file declaration is tagged with IMPORT_C must have its implementation tagged with EXPORT_C. 17. Data should not be exported, but a function provided to modify it (a Set() method) or to return it by reference 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 be derived from in code which is not part of the exporting module. 19. Public or protected functions should not be exported if: (i)

they are not designed for use outside the library

(ii) they are pure virtual functions. 20. Inline functions should never be exported regardless of whether they are public, protected or private.

11

Code Style 21. For efficiency, when initializing member variables in a constructor, the use of member initialization lists should be preferred over assignment statements. 22. The member data of a C class does not require explicit initialization to zero. 23. When testing Booleans, do not use explicit comparison. You should use if(iComplete) instead of if(iComplete==ETrue). 24. When testing pointer values for NULL, it is unnecessary to use explicit comparison, and you should prefer to use if(ptr) over if(ptr!=NULL), unless writing the comparison in full clarifies the intent of the code. 25. Explicit comparison should be used when testing integers: use if(aLength!=0) rather than if(aLength). 26. To avoid scope bloat, automatic variables should not be declared until required, and should be declared as close as possible to their point of use. 27. Stack use should be minimized as much as is possible, for example, use the heap to store large data structures instead of the stack and take care

12 when declaring larger stack-based variables within loops or recursive functions. Use of the TFileName and TParse classes is a common cause of stack consumption, because objects of both types are over 512 bytes in size (remember that the default stack size is only 8KB). 28. Hard-coded ‘magic’ numbers should be avoided. Constants or enumerations should be preferred instead. 29. The concrete types defined in e32def.h should be used in lieu of the language-defined basic types. For example, TInt should be used instead of int. 30. Symbian OS descriptor classes should be used in preference to native strings and memory buffers or alternative, hand-crafted string classes. 31. The _L macro for literal descriptors should not be used except where it is convenient to do so in test code. Prefer to use the _LIT macro for literal descriptors. 32. When using descriptors as function parameters, the base classes (TDes and TDesC) should be used, and should be passed by reference.

13 33. The Symbian OS date and time classes (such as TDateTime and TTime) should be used instead of hand-crafted alternatives. 34. In switch statements, the use of fall-through in a case statement should be commented to convey the intent. A switch statement should also always contain a default statement, even if this does nothing but assert that it is never reached. 35. C++ style casts (for example, static_cast(expression)) should be used in preference to C style casts. The Symbian OS macros for the C++ cast operators (for example, STATIC_CAST(type, expression)) should not be used, because they are deprecated.

36. Code in a loop should terminate for all possible inputs. 37. Thin templates should be used for templated code, to ensure the smallest possible code size while still gaining the benefits of C++ templates. 38. The use of writable global data should be avoided, where possible, in DLLs.

14

Construction 39. The code inside a C++ constructor should not leave. 40. Construction and initialization code that is non-trivial and could fail should be implemented in the second phase of a two-phase constructor, typically in a ConstructL() method. 41. Where two-phase construction is used, one or more public static factory functions (typically called NewL() and NewLC()) should be provided for object construction. The construction methods themselves should be private or protected.

Destruction 42. When de-referencing a pointer in a destructor, the validity of the pointer should first be checked in case it has not been initialized or it has already been destroyed by another destructor in the inheritance hierarchy. 43. It is inefficient and unnecessary to set pointers to NULL in a destructor, unless it is likely to be dereferenced elsewhere during destruction, for example, in the destructor of a superclass.

15 44. Pointers that are deleted outside of a destructor that can later be accessed (for example, member variable pointers) should be set to NULL or immediately reassigned. 45. Resource handles and heap-based member data should be cleaned up in a destructor if they are owned by a class. 46. A destructor should not be able to leave or to throw any type of C++ exception. 47. A TRAP may be used within a destructor of a class stored on the heap, but it is not safe to use a TRAP within any destructor that may be called as the stack unwinds. 48. If an object is being deleted, it should not be on the cleanup stack. 49. If an object has been allocated by a call to new, it should be de-allocated by calling delete . Likewise, a C++ array allocated using new [] should be de-allocated by calling delete [] . For allocations made by calling User::Alloc(), deallocation should be made by calling User::Free().

16

Exception Handling and Memory Management 50. When memory is allocated on the heap, to determine whether the allocation succeeded or failed, either the leaving overload of operator new should be used (new(ELeave)) , or the pointer returned from the call to allocate the memory should be checked against NULL. 51. The cleanup stack should be used to avoid orphaning of memory or resources in the event of a leave. 52. An object should not be simultaneously owned by another object and on the cleanup stack. This means that class member data should never be placed on the cleanup stack if it is also destroyed in the class destructor, 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, those objects should not also be pushed onto the cleanup stack explicitly or they will be present twice. 54. When calling code that can throw a C++ exception, catch everything and convert the exceptions to leaves. TRAP and TRAPD will panic if they receive a C++ exception which was not one raised by a Symbian leave (i.e., of type XLeaveException).

17

Defensive Programming 55. The checking methods of CleanupStack::Pop() and CleanupStack::PopAndDestroy() should be used where possible, to check that PushL() and Pop() calls are balanced. 56. Use the __ASSERT_DEBUG assertion macro liberally to detect programming errors. It may sometimes also be appropriate to use __ASSERT_ALWAYS to catch invalid runtime input. 57. Assertion statements should not perform ‘side effects’ (for example, they should not modify the value of a variable). 58. Assertion statements should be explained using a comment in the code to document the assumptions they make and render them easier to maintain.

18

Additional Rules 59.

60.

61.

62.

63.

64.

65.

19

Further reading For more information about writing C++ on Symbian OS we recommend the developer titles published by Symbian Press. More information is available at developer.symbian.com/books. We also recommend C++ Coding Standards: 101 Rules, Guidelines and Best Practices by Herb Sutter and Andrei Alexandrescu (2005). Pearson Education, Inc.

20

References Symbian Developer Network newsletter developer.symbian.com/register

Symbian OS FAQ database developer.symbian.com/faqs

Symbian Press developer.symbian.com/books

21

Developer Resources Symbian Developer Network developer.symbian.com

Symbian Developer Network newsletter developer.symbian.com/register

Forum Nokia forum.nokia.com

UIQ Developer Community developer.uiq.com

New from

Games on Symbian OS: A Handbook for Mobile Development This book forms part of the Technology Series from Symbian Press. It describes the key aspects of the mobile games marketplace, with particular emphasis on creating games for smartphones based on Symbian OS v9.x.

Developing Software for Symbian OS, Second Edition This second edition of Developing Software for Symbian OS helps software developers new to Symbian OS to create smartphone applications. The original book has been updated for Symbian OS v9 and now includes a new chapter on application signing and platform security, and updates throughout for Symbian OS v9 and changes to the development environment. Symbian Press: developer.symbian.com/press

New from

Symbian OS Communications Programming, Second Edition Targeting Symbian OS v9.1 and v9.2, Symbian OS Communications Programming - Second Edition will introduce you to the major communications functionality in Symbian OS and demonstrates how to perform common tasks in each area.

Symbian OS C++ for Mobile Phones, Volume 3 This book will help you to become an effective Symbian OS developer, and will give you a deep understanding of the fundamental principles upon which Symbian OS is based.

Symbian Press: developer.symbian.com/press

Also from

The Symbian OS Architecture Sourcebook This book conducts a rapid tour of the architecture of Symbian OS and provides an introduction to the key ideas of object orientation (OO) in software, with a detailed exploration of the architecture of Symbian OS.

S60 Programming Fully up to date for Symbian OS v9 and S60 3rd Edition, S60 Programming is an essential foundation to developing software for Symbian OS. This practical book is based on the authors’ experiences in developing and teaching an academic course on Symbian software development.

Symbian Press: developer.symbian.com/press

Also from

For all Symbian C++ developers: Symbian OS C++ for Mobile Phones – Volume 1 by Richard Harrison Symbian OS C++ for Mobile Phones – Volume 2 by Richard Harrison Symbian OS Explained by Jo Stichbury Symbian OS Internals by Jane Sales Symbian OS Platform Security by Craig Heath Smartphone Operating System Concepts with Symbian OS by Mike Jipping Accredited Symbian Developer Primer by Jo Stichbury & Mark Jacobs

Also from

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 Japanese Korean

Spanish Russian

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. Coding Standards is a booklet in the Essential Symbian OS series, designed to provide information in a handy format for developers working on Symbian OS.

developer.symbian.com/books

Related Documents


More Documents from ""