30
Common Design Patterns for Symbian OS The Foundations of Smartphone Software Lead Author Adrian Issott With Nicholas Addo, Toby Gray, David Harper, Craig Heath, Guruprasad Kini, Ian McDowall, Ben Morris, John Roe, Dale Self, James Steele, Jo Stichbury, Oliver Stuart, Viki Turner, Hamish Willee Reviewed by Sandip Ahluwalia, Matthew Allen, Sorin Basca, David Caabiero, Iain Campbell, Douglas Feather, Ryan Gilmour, Martin Hardman, Richard Harrison, Tim Howes, Mark Jacobs, Martin Jakl, Sian James, Antti Juustila, Simon Mellor, Sihem Merah, Will Palmer, Subhasis Panigrahi, Lucian Piros, Mark Shackman, Adrian Taylor, Paul Todd, Gabor Torok, Charles Weir, Alex Wilbur, Tim Williams Head of Symbian Press Freddie Gjertsen Managing Editor Satu McNabb A John Wiley and Sons, Ltd., Publication

Common Design Patterns for Symbian OSdownload.e-bookshelf.de/download/0000/5792/73/L-G-0000579273...Common Design Patterns for Symbian OS The Foundations of Smartphone ... Milton,

  • Upload
    dothuy

  • View
    216

  • Download
    0

Embed Size (px)

Citation preview

  • Common Design Patternsfor Symbian OSThe Foundations of SmartphoneSoftware

    Lead AuthorAdrian Issott

    WithNicholas Addo, Toby Gray, David Harper, Craig Heath,Guruprasad Kini, Ian McDowall, Ben Morris, John Roe,Dale Self, James Steele, Jo Stichbury, Oliver Stuart, Viki Turner,Hamish Willee

    Reviewed bySandip Ahluwalia, Matthew Allen, Sorin Basca, David Caabiero,Iain Campbell, Douglas Feather, Ryan Gilmour,Martin Hardman, Richard Harrison, Tim Howes, Mark Jacobs,Martin Jakl, Sian James, Antti Juustila, Simon Mellor,Sihem Merah, Will Palmer, Subhasis Panigrahi, Lucian Piros,Mark Shackman, Adrian Taylor, Paul Todd, Gabor Torok,Charles Weir, Alex Wilbur, Tim Williams

    Head of Symbian PressFreddie Gjertsen

    Managing EditorSatu McNabb

    A John Wiley and Sons, Ltd., Publication

    ayyappan9780470713778.jpg

  • Common Design Patternsfor Symbian OS

    The Foundations of Smartphone Software

  • Common Design Patternsfor Symbian OSThe Foundations of SmartphoneSoftware

    Lead AuthorAdrian Issott

    WithNicholas Addo, Toby Gray, David Harper, Craig Heath,Guruprasad Kini, Ian McDowall, Ben Morris, John Roe,Dale Self, James Steele, Jo Stichbury, Oliver Stuart, Viki Turner,Hamish Willee

    Reviewed bySandip Ahluwalia, Matthew Allen, Sorin Basca, David Caabiero,Iain Campbell, Douglas Feather, Ryan Gilmour,Martin Hardman, Richard Harrison, Tim Howes, Mark Jacobs,Martin Jakl, Sian James, Antti Juustila, Simon Mellor,Sihem Merah, Will Palmer, Subhasis Panigrahi, Lucian Piros,Mark Shackman, Adrian Taylor, Paul Todd, Gabor Torok,Charles Weir, Alex Wilbur, Tim Williams

    Head of Symbian PressFreddie Gjertsen

    Managing EditorSatu McNabb

    A John Wiley and Sons, Ltd., Publication

  • Copyright 2008 John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester,West Sussex PO19 8SQ, England

    Telephone (+44) 1243 779777Email (for orders and customer service enquiries): [email protected] our Home Page on www.wileyeurope.com or www.wiley.com

    All Rights Reserved. No part of this publication may be reproduced, stored in a retrieval system ortransmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning orotherwise, except under the terms of the Copyright, Designs and Patents Act 1988 or under the terms ofa licence issued by the Copyright Licensing Agency Ltd, 90 Tottenham Court Road, London W1T 4LP,UK, without the permission in writing of the Publisher. Requests to the Publisher should be addressed tothe Permissions Department, John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, WestSussex PO19 8SQ, England, or emailed to [email protected], or faxed to (+44) 1243 770620.Designations used by companies to distinguish their products are often claimed as trademarks. Allbrand names and product names used in this book are trade names, service marks, trademarks orregistered trademarks of their respective owners. The Publisher is not associated with any product orvendor mentioned in this book.

    This publication is designed to provide accurate and authoritative information in regard to the subjectmatter covered. It is sold on the understanding that the Publisher is not engaged in renderingprofessional services. If professional advice or other expert assistance is required, the services of acompetent professional should be sought.

    Other Wiley Editorial Offices

    John Wiley & Sons Inc., 111 River Street, Hoboken, NJ 07030, USA

    Jossey-Bass, 989 Market Street, San Francisco, CA 94103-1741, USA

    Wiley-VCH Verlag GmbH, Boschstr. 12, D-69469 Weinheim, Germany

    John Wiley & Sons Australia Ltd, 42 McDougall Street, Milton, Queensland 4064, Australia

    John Wiley & Sons (Asia) Pte Ltd, 2 Clementi Loop #02-01, Jin Xing Distripark, Singapore 129809

    John Wiley & Sons Canada Ltd, 6045 Freemont Blvd, Mississauga, Ontario, L5R 4J3, Canada

    Wiley also publishes its books in a variety of electronic formats. Some content that appearsin print may not be available in electronic books.

    British Library Cataloguing in Publication Data

    A catalogue record for this book is available from the British Library

    ISBN 978-0-470-51635-5

    Typeset in 10/12 Optima by Laserwords Private Limited, Chennai, IndiaPrinted and bound in Great Britain by Bell & Bain, GlasgowThis book is printed on acid-free paper responsibly manufactured from sustainable forestryin which at least two trees are planted for each one used for paper production.

    www.wiley.com

  • Dedicated to Kat and to Mike

  • Contents

    Author Biographies ix

    Authors Acknowledgments xv

    Foreword xvii

    Glossary xix

    1 Introduction 11.1 About this Book 11.2 Who this Book Is For 11.3 Which Version of Symbian OS this Book Is For 21.4 General Design Patterns 21.5 Symbian OS Patterns 41.6 Design Pattern Template 101.7 Structure of this Book 121.8 Conventions 131.9 Other Sources of Information 13

    2 Error-Handling Strategies 15Fail Fast 17Escalate Errors 32

    3 Resource Lifetimes 49Immortal 53

  • viii CONTENTS

    Lazy Allocation 63Lazy De-allocation 73

    4 Event-Driven Programming 87Event Mixin 93Request Completion 104Publish and Subscribe 114

    5 Cooperative Multitasking 131Active Objects 133Asynchronous Controller 148

    6 Providing Services 165Client-Thread Service 171ClientServer 182Coordinator 211

    7 Security 233Secure Agent 240Buckle 252Quarantine 260Cradle 273

    8 Optimizing Execution Time 287Episodes 289Data Press 309

    9 Mapping Well-Known Patterns onto Symbian OS 331ModelViewController 332Singleton 346Adapter 372HandleBody 385

    Appendix: Impact Analysis of RecurringConsequences 397

    References 403

    Index 407

  • Author Biographies

    Nicholas Addo

    Nicholas has worked on Symbian OS for six years. He first joined theBrowser Technology group in Symbian, developing a generic frameworkfor content handling. He then moved to the Personal Information Man-agement group to work on Enterprise Group Scheduling technology.From there, he joined the Multi-technology development group to workon cross-technology and process-improvement projects. This included astint in product management defining a Component Technology productstrategy for Symbian OS and an ongoing involvement in improvementinitiatives for Symbian OS core idioms.

    Nicholas started his career as an apprentice Electronics Engineer in the1980s, developing semiconductor devices for telecommunications. Hemoved into a solely software development career in the 1990s. This wasinitially in real-time embedded systems and later Windows-based userinterfaces for image scanners, writers, and print register and color controldevices for the printing and pre-press industry.

    Toby Gray

    Toby has worked with Symbian OS since joining the System Managementgroup of Symbian in 2005. Since then, he has worked on topics rangingfrom optimizing system characteristics (e.g. speed, RAM usage and ROMusage) to management of system start-up and from development ofdiagnostic tools to ARM assembler optimization. He holds a BA inComputer Science from the University of Cambridge.

  • x AUTHOR BIOGRAPHIES

    David Harper

    David has worked at Psion Software and Symbian for over 10 years.During that time he has developed an in-depth knowledge of HTTP,Internet technologies, ECom and Platform Security. He now works inIntegration Management, specializing in Technology Integration. Davidholds an MSc in Artificial Intelligence from Queen Mary and WestfieldCollege.

    Craig Heath

    Craig has been working in IT security since 1988, with The Santa CruzOperation as security architect for SCO UNIX, then at Lutris Technologiesas security architect for their Java Enterprise Application Server. Hejoined Symbian in 2002, working in product management and strategy.He has contributed to several published industry standards and hasa long association with The Open Group Security Forum, includingco-authorship of the Open Group Technical Guide to Security DesignPatterns. Craig is lead author of Symbian OS Platform Security.

    Adrian Issott

    Adrian joined Symbians Shortlink team in 2004 working first on devel-oping support for Bluetooth stereo headsets and then on enhancing theBluetooth HAI. In 2006, he moved on to become an architect focusingon system characteristics such as performance, RAM usage, reliabilityand security. His time is currently spent either working on long-termarchitectural improvements in areas such as system start-up and trace oron urgent projects helping device manufacturers optimize their devicesand get the best out of Symbian OS. Adrian graduated from Jesus College,Oxford with a first class honors degree in Mathematics.

    Guruprasad Kini

    Guru has been working with Symbian for the last three and a half years,most of which he spent in the Remote Management Team. He is nowa part of the Systems Engineering Team. Design patterns, cryptographyand data security have been his primary professional interests. Guru isbased near Bangalore and holds a BE in Computer Science from ManipalInstitute of Technology, Karnataka. He hopes to retire early and do whathe always wanted to do teach mathematics in schools. And . . . oh yes,he is also very bad at writing bios.

  • AUTHOR BIOGRAPHIES xi

    Ian McDowall

    Ian joined Symbian in 2001, has worked in a range of teams withinSymbian and is currently a Technology Architect responsible for Short-link technologies. He has previously filled roles ranging from developerthrough project manager to technical manager. He has an MA in Com-puter Sciences from Cambridge University and an MBA from WarwickUniversity. As a software engineer for over 25 years, he has workedfor a number of software companies and has worked on more than 15operating systems, developing software ranging from enterprise systemsto embedded software. He is married to Lorraine and they have twochildren, Kelly and Ross, and a number of pets.

    Ben Morris

    Ben joined Psion Software in October 1997, working in the softwaredevelopment kit team on the production of the first C++ and Java SDKsfor what was at that time still the EPOC32 operating system. He led thesmall team that produced the SDKs for the ER5 release of EPOC32 and,when Psion Software became Symbian, he took over responsibility forexpanding and leading the companys system documentation team. In2002, he joined the newly formed System Management Group in theSoftware Engineering organization of Symbian, with a brief to definethe system. He devised the original system model for Symbian OS andcurrently leads the team responsible for its maintenance and evolution.He can be found on the Internet at www.benmorris.eu.

    John Roe

    John has an MA in Engineering from Cambridge University and hasworked with Symbian for well over 10 years. For the past nine years, hehas been in Symbians Customer Engineering group as the S60 TechnicalLead. He has worked on S60 since its inception and on many S60 phonesranging from the Nokia 7650 to present-day devices. He divides his timebetween supporting Symbians licensees and using his product realizationexperience to develop the architecture of Symbian OS.

    Dale Self

    Dale is soon to celebrate 10 years of working for Symbian, where heworked first in the Messaging team on IMAP and later in the Shortlink

  • xii AUTHOR BIOGRAPHIES

    team on Bluetooth and OBEX. Most recently, he has been working onUSB architecture and standardization. In his spare time, he enjoys music,photography and writing fiction as well as non-fiction. He hopes that hiscontribution to this book falls into the latter category.

    James Steele

    James joined Symbian after graduating from university in 2004. Heattended the University of Cambridge (Fitzwilliam College) where heread Computer Science. Since starting his career at Symbian as a memberof the Shortlink team he has been involved with the development ofnumerous protocol stacks, including Bluetooth, USB and IrDA.

    In his free time, James enjoys taking part in friendly poker matcheswith friends and colleagues, and pretending to be a film critic. He playsvarious sports, including basketball, badminton and squash. In the winter,you will probably find him skiing somewhere in the French Alps.

    Jo Stichbury

    Jo is Senior Technical Editor with Symbian Press. She has worked withinthe Symbian ecosystem since 1997 in the Base, Connectivity and Securityteams of Symbian, as well as for Advansys, Sony Ericsson and Nokia. Jois the author of Symbian OS Explained: Effective C++ programming forsmartphones, published by Symbian Press in 2004. She also coauthoredThe Accredited Symbian Developer Primer: Fundamentals of SymbianOS with Mark Jacobs, in 2006. Her most recent book is Games onSymbian OS: A handbook for mobile development, published in early2008.

    Oliver Stuart

    Oliver is a recent convert to Symbian and joined the companys Commsteam in 2007. Thrown in at the deep end, he has enjoyed the challengingwork of developing for a powerful mobile operating system. He previouslyworked in the field of biological digital imaging at Improvision Ltd andhas interests in object-oriented programming, concurrency, networkingand multimedia. He holds a BSc with Hons in Computer Science/SoftwareEngineering from the University of Birmingham in the UK. He has carefullytried to hide his past as a Windows developer from his new colleagues toavoid derision.

  • AUTHOR BIOGRAPHIES xiii

    Viki Turner

    Viki is the Comms Chief Technology Architect at Symbian. She has workedwith communications technologies at Symbian since joining in 2001,when she helped the third Symbian phone to ship successfully. In earlierengineering roles, she also developed communications middleware first with an interesting but short-lived startup, developing a networkedmultimedia distribution platform, and then working in the City of Londonon data feed products. Viki trained in computing at Imperial College, aftera few years pursuing a career as a classical soprano . . . but thats anotherstory.

    Hamish Willee

    Hamish joined Symbian in late 1998 and is looking forward to the10 year celebrations! Most of those years were spent in developer supportroles he still gets a kick out of improving third-party development onSymbian OS. The last few years he has worked remotely from Melbourne,Australia, continuing to provide technical assistance to Symbians globaldeveloper ecosystem. Outside work, Hamish loves to spend time with hisfamily: Jen, Oscar, Sam and Leo.

  • Authors Acknowledgments

    We would like to thank:

    The individual authors who worked long and hard not only to describethe patterns but also to refine the key ideas that needed to be expressed.

    All the technical reviewers who corrected and enhanced the text. Jo Stichbury who helped at every step of the way with insightful advice

    on how to improve the book as well as authoring a pattern herself.

    Satu McNabb who kept us focused on delivering to our deadlines. Charles Weir who helped to ensure the patterns dont just document

    how Symbian OS is architected but are accessible to developersbuilding on Symbian OS. His positive attitude was also very welcome!

    Everyone else in Symbian who helped us along the way especially IanMcDowall, John Roe, Matthew Reynolds and Michael Harper.

    Our friends and families who, throughout the long process of preparingthis book, didnt see as much of us as they had the right to expect.

  • Foreword

    This book gives you an insight into the worlds most successful smartphoneoperating system. As this book goes to press, over 200 million Symbiansmartphones have shipped worldwide twice as many as all other typesof smartphone put together. Its a huge potential market for applicationsand add-in software.

    Symbian OS is a very powerful environment; writing the most effectivesoftware for it means learning the Symbian dialect of C++ and thinkingin the idioms it uses. Who better to teach that than some of the softwarearchitects who designed the operating system in the first place? Adrianand his team have produced a book that teaches you to think in SymbianOS. Other books can teach you the mechanics of the language how touse the GUI, the networking APIs and the application infrastructure butthis book helps you to develop a feel for the way a complex applicationshould fit together, which is much more difficult.

    My own involvement with Symbian OS included being technicalarchitect for the first Symbian OS phone, co-authoring a patterns book onlimited memory software, and running Penrillian, a company specializingin porting software to Symbian OS. All these roles have emphasized for mejust how much mobile phone development differs from traditional desktopand server programming. Symbian OS is very strong in two features:effective use of power and avoiding resource leaks when handling errorconditions. Teaching developers the design techniques to keep softwareconforming to these has been a major task for me; these patterns make itstraightforward.

    This work builds on the introductions to Symbian OS in other SymbianPress books. Even if you already have a good understanding of how to useleaves and traps, active objects, GUI controls and the communicationsAPIs, youll need to know how to design effective architectures and

  • xviii FOREWORD

    component interfaces to use them effectively. Thats why this book isso valuable. It describes the thinking of the architects who designedSymbian OS, its applications and infrastructure, and tells us, in bite-sizedpieces, how they did it so that we can build on their work. As a seasonedSymbian OS programmer, I learnt something new from the descriptionsof managing secure plug-ins and the process-coordination patterns. If youdont have much experience on Symbian OS, you will particularly valuethe explanation and idioms of inter-process communication, resourcemanagement and event handling.

    How does the pattern format help you to learn? A book of patternsis half way between a descriptive volume and a reference text. You canread each pattern as a separate paper, but the prescriptive pattern formatalso makes it easy to skim through all the patterns and see which onescover which ground. So please dont think of this as a book to read fromcover-to-cover (though you can do that if you like). Instead you can usethe way its set out to skim through the overviews of each pattern: thenames, intent, and descriptions and read as much as you like of eachof the patterns you find interesting or use a lot already. As you work onSymbian OS projects and designs, youll find yourself with problems thatremind you of one or more of the solutions in the book and that is thetime to go back and look for the detail of the implementation. The bookbecomes the experienced designer leaning over your shoulder sayingoh yes, have a look at such-and-such for the way to do it, and dontforget thus-and-this issues to consider. And its experienced designersthat make architecture great.

    So take a look. No matter who you are, I challenge you not to finda technique or an implementation of a technique thats interesting toyou. And youll find, as I did, that you can learn a lot about how best todesign Symbian OS applications and services. Heres wishing you successdesigning software for the most popular mobile platform in the world!

    Charles WeirPenrillian, 2008

  • Glossary

    Word Definition

    ABI Application Binary Interface.

    AO Active Object.

    Applicationdeveloper

    A person who develops applications for Symbian OS that run on top of aspecific UI Layer. Often such applications do not form part of a ROM andare installed onto a device after it has been created in a factory.

    Base portprovider

    A company that provides the base port required to get Symbian OS workingon specific device hardware.

    Binarycompatibility

    This is less restrictive than full compatibility in that it states only that a clientexecutable does not need to be re-compiled for it to work with all versionsof the binary compatible executable.

    Compatibility Software is said to be compatible if the clients of one version of the softwarecan also be run on all other versions of the software without any changesbeing needed to the clients.

    Component A block of code that performs a particular function at an interesting levelof functionality.

    CPM Communication provider module.

    Device creator A developer of software that is integrated into a ROM during devicemanufacture. Device creators most commonly work for Symbian, a UIvendor or a base port provider but could also be one of their suppliers.

    DLL loadingrule

    A process can only load a DLL if that DLL has been trusted with at least thecapabilities that the process has.

  • xx GLOSSARY

    Word Definition

    DRM Digital rights management (DRM) refers to technologies used by publishersand copyright holders to control access to and usage of digital media.

    Ephemeralresources

    Resources such as CPU cycles and battery power are ephemeral. Their keytrait is that you cant hold on to them or reserve them for your own use.Theyre there but you cant keep a grip on them whether you use them ornot.

    Executable A file whose contents are meant to be interpreted as a program by acomputer. Not just EXE files but DLLs and other file types as well.

    Framework A framework provides a reusable design for a software system or subsystem.It is expressed as a set of abstract classes and the way their instances col-laborate, with the intent of facilitating software development by allowingdevelopers to spend more time on meeting software requirements ratherthan dealing with the more tedious low-level details of providing a workingsystem. Before a framework can be deployed it needs to be specialized fora particular use. This can either be done at build time via static depen-dencies between software modules or at run time via dynamically loadedplug-ins.

    ICL Image Conversion Library, part of the Symbian OS multimedia subsystem.

    IPC Inter-Process Communication.

    LDD Logical Device Driver.

    Mixin An abstract interface that provides a certain functionality to be inherited bya class. The Symbian OS naming convention for these classes is that theystart with an M.

    MMU Memory Management Unit.

    Non-XIP A device which is not XIP-based stores code on disk, usually compressedin some way, and loads it into RAM to be run. This is in addition to theRAM used for the run-time data for each instance. Non-XIP devices basedon Symbian OS are currently the most common type outside Japan.

    Ownableresources

    Resources such as RAM, disk space and communication channels areownable. Unlike ephemeral resources, you can hold onto them and keepusing them. Such resources can be reserved for your sole use.

    PDD Physical Device Driver.

    Plug-in A software module loaded at run time to add a specific feature or service toa larger software module.

    Polling This is where a software object periodically requests information. This is theopposite of event-driven programming, in which the software object wouldwait to be notified of any changes to the information it is interested in.

  • GLOSSARY xxi

    Word Definition

    Racecondition

    This is a flaw in a system or process whereby the output or result of theprocess is unexpectedly and critically dependent on the sequence or timingof other events. The term originates with the idea of two signals racing eachother to influence the output first.

    RAM Random Access Memory.

    Real time This is a constraint on an operation in which the time between starting andfinishing it must be within a fixed limit.

    Resource Any physical or virtual entity of limited availability that needs to be sharedacross the system.

    SDL This is the Symbian Developer Library which can be found in every deviceSDK as well as online at developer.symbian.com/main/documentation/sdl .

    Sourcecompatibility

    This is less restrictive than full compatibility as it states only that no sourcecode changes need to be made for a client to work across all versions of thesoftware.

    Stray signal This is when a request has been signalled as complete but either there is noactive object available or an active object is found that has neither been setactive nor has a request pending.

    SWI Software Installer.

    TCB Trusted Computing Base can refer to a capability or to the components thatuse the capability, such as the kernel, the file server and, on open devices,the software installer. These components have unrestricted access to thedevice resources. They are responsible for maintaining the integrity of thedevice and applying the fundamental rules of platform security. The rest ofthe operating system must trust these components to behave correctly andas a result, their code will have been very strictly reviewed.

    TCE Beyond the TCB, other system components are granted orthogonal restrictedsystem capabilities and constitute the Trusted Computing Environment.This includes servers providing sockets, telephony, certificate management,database access, and windowing services. Each server has just the capa-bilities it requires; for instance, the windowing server is not granted phonestack access and the communications server is not granted direct access tokeyboard events.

    TCP Transmission Control Protocol.

    UDP User Datagram Protocol.

    UI vendor A company that provides the user interface layers on top of Symbian OSwhich, along with a base port, is needed to create platforms from whichdevices can be created. The current UI layers are MOAP, S60 and UIQ.

  • xxii GLOSSARY

    Word Definition

    Vendor A company or person that provides software for use on a Symbian OSdevice.

    WSD Writable Static Data is any modifiable globally-scoped variable declaredoutside of a function, or any function-scoped static variables.

    XIP An eXecute-In-Place device is one in which code is stored and run directlyfrom disk. This means that the code does not take up any RAM when runalthough each instance still uses RAM for its run-time data, such as itsprogram stack, etc. XIP devices based on Symbian OS are currently the mostcommon type in Japan.

  • 1Introduction

    1.1 About this Book

    If youve ever asked yourself How do the experts architect software formobile devices? then this book is for you. Common Design Patterns forSymbian OS collects the wisdom and experience of some of Symbiansfinest software engineers. It distils their knowledge into a set of commondesign patterns that you can use when creating software for Symbiansmartphones.

    This book helps you negotiate the obstacles often found when workingon a smartphone platform. Knowing the potential problems, and thepatterns used to solve them, will give you a head start in designingand implementing robust and efficient applications and services onSymbian OS.

    This book is not intended to be a quick start guide to Symbian OS,nor to explain its design or architecture. Other titles from Symbian Pressdo just that, for example [Harrison and Shackman, 2007] and [Morris,2007]. Rather, it aims to capture expert knowledge about programmingpractice specific to Symbian OS and make it available to all developersworking with Symbian OS.

    We welcome your feedback and contributions and so we have pro-vided a wiki page at developer.symbian.com/design patterns wikipagewhere you can post your experiences with the patterns we describe andshare additional patterns that you know of for Symbian OS.

    1.2 Who this Book Is For

    This book is suitable for relative beginners as well as experts in SymbianOS development. It will help beginners to make progress quickly whenworking on medium-sized projects. It will also support experts in theirdesign of large-scale and sophisticated software and assist them in learning

  • 2 INTRODUCTION

    from the experience of other experts. The book should help both groups toharness well-proven solutions, as well as specific variations, to individualdesign problems.

    To get the most out of the book, readers are expected to have someexisting knowledge of Symbian OS and C++, so basic concepts are notexplained in detail. For instance, we assume that you are aware of someof the basic idioms, such as descriptors, and have an understandingof the basic types of Symbian OS classes (e.g. C, R, T and M classes)and how they behave. The book specifically targets existing SymbianC++ developers whether theyre creating applications or services. Itcan equally well be used by developers internal to Symbian, licenseedevelopers creating devices and third-party developers writing after-market applications.

    If you are new to Symbian OS or want to take a refresher course inthese concepts, there are several books that you could read, including[Harrison and Shackman, 2007] and [Stichbury and Jacobs, 2006], whichdescribe the basics of Symbian C++ development.

    1.3 Which Version of Symbian OS this Book Is For

    This book applies to Symbian OS v9.1 and onwards, which means that allthe patterns described work in all v9.x releases. However, a number of thepatterns are not specific to any particular version of Symbian OS and cantherefore be applied to earlier versions of the operating system as well.

    The patterns contained in this book are also expected to be equallyapplicable to any future version of the Symbian platform. While some ofthe details of the operating system may well change, it is unlikely thatthere will be significant differences that impact the level of abstraction inwhich the patterns of this book are described.

    1.4 General Design Patterns

    The genre of software design pattern books was established with thepublication of the Gang of Four book [Gamma et al., 1994] in the 1990s.Since then a profusion of design pattern books have been published,including a small number explicitly for embedded systems, of which[Weir and Noble, 2000] is a good example.

    The aim of all of these books is to capture the collective experienceof skilled software engineers based on proven examples so as to helppromote good design practices. This is achieved through the creation of

  • GENERAL DESIGN PATTERNS 3

    design patterns, commonly defined to be solutions to a problem in acontext. The process of creating a design pattern reflects the way thatexperts, not just in software engineering but in many other domainsas well, solve problems. In most cases, an expert will draw on theirexperiences of solving a similar problem and reuse the same strategiesto resolve the problem at hand. Only rarely will a problem be solved inan entirely unique fashion. Design patterns are established by looking forcommon elements in the solutions to similar problems.

    The Introduction to [Gamma et al., 1994] and the Patterns chapter of[Buschmann et al., 1996] provide a good discussion of pattern theory sowe instead focus on how to get the best out of design patterns. Mostpeople start with a design problem that theyre not sure how to solveand so might start flipping through a design patterns book like this onelooking for inspiration. Each of the patterns is written in such a waythat it should be as easy as possible to quickly understand whether itsdescribing a solution to the problem youre concerned with and whetheritll help you construct software with the properties you require. Onceyouve identified a pattern that looks like it should help, you should takesome time to customize it for your specific circumstances. Ideally, usinga pattern is comparable to approaching a problem as if youve solvedsomething similar in a previous project. Then when youre reviewing,implementing or documenting your software using a well-defined patterngives you a common vocabulary to help communicate to other engineersinvolved in the project how your software is designed.

    Here are some important things to keep in mind when using patterns:

    All patterns have negative consequences in addition to the positivereasons that lead you to consider a given pattern in the first place.These negatives also need to be taken into account when choosingwhether or not to use a pattern.

    You dont get points for using as many patterns as possible whensolving a single problem. Patterns should only be used when they areactually needed. The main reason for this is that using too many canresult in overly complicated solutions caused by the additional levelsof abstraction that they generally introduce.

    Patterns are not intended to be used as fixed templates and applieddirectly to your software without thinking. Instead they should be usedas a guide to get you most of the way towards describing a workingsolution. Its up to you to finish off the design process and ensure thatyour specific solution respects the details of your situation.

    Patterns are often very useful tools but only when applied to the rightjobs.

  • 4 INTRODUCTION

    1.5 Symbian OS Patterns

    Thats all very well but whats this got to do with Symbian OS? Well, oneproblem with patterns is that, because they have been abstracted awayfrom specific problems, it can be hard to understand how best to applythem. One of the goals of this book is to describe a set of patterns in moretangible terms specific to Symbian OS and so make them easier to applyin a Symbian OS context. This will be done via the following means:

    Each pattern describes how the forces most relevant to an embeddedoperating system, such as Symbian OS, impact and are changed bythe patterns.

    Explanations are given to explain how Symbian OS architecturalelements can be re-used in the application of the patterns.

    Code samples are given in terms of Symbian OS APIs and codingstandards so that as much as possible of your job of translating apattern into practice has already been done for you.

    Examples based on Symbian OS are given to show how the patternshave been realized in situations that Symbian OS developers canmore easily relate to.

    1.5.1 Constraints on Software Based on Symbian OS

    The constraints on a mobile device platform means that software devel-opment for Symbian OS has to resolve a set of forces that are distinctfrom those found in desktop or enterprise environments. Consider thefollowing list of constraints imposed by the mobile device environment:

    Constrained hardwareCompared to mainstream laptops, mobile devices are between 10and 30 times smaller in terms of CPU speed, RAM size and storagespace and are set to remain so in relative terms even as they increasein absolute terms. This is partly to do with the fact that mobiledevices are expected to be carried around in your pocket all thetime, putting both size and weight constraints on the devices. Anotherfactor is the fact that with over 7 million Symbian OS devices nowbeing sold each month,1 device manufacturers are keen to maximizetheir profits by keeping the cost of the materials in each device aslow as possible. Increasing the instructions processed per secondmeans including a faster CPU; boosting the memory available tothe system means including a bigger RAM chip. When shippingpotentially millions of each product, even small savings per deviceadd up quickly. Also, if an end user finds that a device frequently runs

    1www.symbian.com/news/pr/2008/pr20089781.html.

  • SYMBIAN OS PATTERNS 5

    out of resources, they cant just plug in a new bit of hardware as theycan on a PC.

    Limited power supplyUnlike fixed desktop computers or enterprise servers, mobile deviceshave to run from a battery. This limited power supply has to becarefully conserved so that the device can stay active for as long aspossible, especially because battery life is one of the top requirementsof end users. This constraint means that peripherals such as antennas,RAM chips, CPU, the screen, and so on, should all be used as little aspossible or used at a reduced rate to save power.

    Expectations of high reliabilityEnd users expect and demand rock-solid stability and reliability fromtheir mobile devices; desktop levels of quality are not acceptable.One of the drivers for this is the fact that mobile devices can be alife-saving tool whether its to make an emergency phone call or toallow the rescue services to locate you if youve had an accident. Anadditional factor is that it is relatively easy for an end user to switchbetween mobile devices; any devices that dont measure up to thisstandard are returned to the manufacturer.

    Open operating systemA key difference between Symbian OS and many other embeddeddevices is that the operating system allows the software on a deviceto be extended and upgraded after it has been shipped from thefactory and is in the hands of an end user. Hence, software cannot beoptimized for specific tasks or rely on events occurring in a set order.Software based on Symbian OS needs to be flexible, adaptable andallow for future changes.

    Note that whilst upgrades are possible on a mobile device, theyreusually restricted to functionality upgrades rather than providing defectfixes. This is because getting the upgrade onto the device may welltake longer and may cost the user money if it is sent over the phonenetwork. Frequent updates would also increase the chance of mistakesoccurring and hence affect the reliability of the device unless carefullycontrolled.

    Expectations of high securityAll of the stakeholders in mobile devices users, device manu-facturers, retail vendors, network operators, and suppliers ofsoftware, services, and content expect them to be secure againstsoftware attacks. The risks include end users losing their private data,content producers having their DRM files stolen and damage to thereputation of device manufacturers. The risks to mobile devices aresignificant because Symbian OS allows software to be installed: thereare multiple communication channels to and from the device, they

  • 6 INTRODUCTION

    often contain lots of private information, and they support a number ofservices that can incur charges through operator tariffs, premium-ratemessages, and so on.

    Restricted user interfaceDue to the small size of mobile devices not only are the screen sizessmall but they also suffer from minimal keyboards, if a keyboard ispresent at all, and other restricted human interface mechanisms. Thismeans that user interfaces have to be made simpler. In addition, theyneed to be more adaptable than in larger devices because the enduser is more likely to make an error in interacting with the device.Note that this constraint mainly affects applications rather than theunderlying services.

    1.5.2 Important Forces in the Context of Symbian OS

    The constraints listed in Section 1.5.1 lead to the following importantforces for software based on Symbian OS:

    Minimal use of RAMRandom Access Memory (RAM) is a type of computer data storage.A key characteristic of RAM is that it is volatile and information itcontains is lost when a device is turned off. The three main contributorsto RAM are:

    Call stack a dynamic data structure which stores informationabout the current execution including details of the active functionsand local data

    Heap an area of memory that you can dynamically allocate fromusing the new operator; free store is another name for a heap

    Code devices that are not eXecute-In-Place (XIP) based load codefrom secondary storage into RAM where it is executed. Exactlyhow this is done depends on the memory model used but codecan make up a significant proportion of the RAM used on a device.

    The main motivation for reducing RAM is simply because there isa limited amount available on the device. However, a secondaryconsideration is that power is required to store data in RAM soreducing RAM can also result in less power usage. On the other hand,minimizing RAM usage can be at the cost of increasing the executiontime if, for example, you reduce cache sizes.

    Predictable RAM usageA necessary consequence of having limited RAM available is that atsome point it will run out. For some situations this can have catas-trophic consequences for your device. For instance, if an end user istrying to call for an ambulance, the phone shouldnt fail because the