Главная » Просмотр файлов » Symbian OS Explained - Effective C++ Programming For Smartphones (2005)

Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885), страница 59

Файл №779885 Symbian OS Explained - Effective C++ Programming For Smartphones (2005) (Symbian Books) 59 страницаSymbian OS Explained - Effective C++ Programming For Smartphones (2005) (779885) страница 592018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 59)

However, if you prefer not to display and log this additionalinformation, you should simply give the RTest object a variable nameother than test.All the RTest functions which display data on the screen also send itto the debug output using a call to RDebug::Print(). If you’re runningthe code on the Windows emulator, this function passes the descriptorto the debugger for output. On hardware, the function uses a serial portwhich can be connected to a PC running a terminal emulator to viewthe output (for this output, of course, you need a spare serial port on thephone and a connection to a PC). You can set the port that should beused by calling Hal::Set(EDebugPort,aPortNumber). You’ll finda debug log can be extremely useful when running your code on thephone as you develop it. Class RDebug is defined in e32svr.h andprovides a number of other useful functions, such as support for profiling.On the emulator, the debug output is also written to file, so you canrun a batch of tests and inspect the output of each later.

The emulatoruses the TEMP environment variable to determine where to store the file,which it names epocwind.out (%TEMP%\epocwind.out).33On Windows NT this is usually C:\TEMP, while on versions of Windows later thanWindows 2000, each user has a temporary directory under their Local Settings folder(C:\Documents and Settings\UserName\Local Settings\Temp). Of course, youcan change the TEMP environment variable to any location you want to make access to thisfile convenient.276DEBUG MACROS AND TEST CLASSESI’ve not illustrated the use of RTest::Printf() andRTest::Getch() in the example code, but they can be used in muchthe way you would expect, to print to the display/debug output and waitfor an input character respectively.Class RTest is useful for test code that runs in a simple console, andcan be used to check conditional expressions, raising a panic if aresult is false.

If you want to use the cleanup stack in console-basedtest code, or link against a component which does so, you will needto create a cleanup stack as discussed in Chapter 3. If you write orlink against any code which uses active objects, you will need tocreate an active scheduler, as described in Chapters 8 and 9.17.4SummaryMemory is a limited resource on Symbian OS and must be managedcarefully to ensure it is not wasted by memory leaks. In addition, anapplication must handle gracefully any exceptional conditions arisingwhen memory resources are exhausted. Symbian OS provides a set ofdebug-only macros that can be added directly to code to check both thatit is well-behaved and that it copes with out-of-memory conditions. Thischapter described how to use the macros, and how to debug your codeto find the root cause when the heap-checking code panics to indicate aheap inconsistency.The chapter also discussed how to use the object invariance macrothat Symbian OS provides to verify the state of an object.

The macrocan be added to any class and offers the opportunity to write customizeddebug state-checking for objects of the class.Finally, the chapter described the RTest class, which is useful forconsole-based test code. The API for RTest can be found in e32test.hand is not published, so it may be changed without notice but, since itis used internally by Symbian OS test code, it is unlikely to be removed.RTest can be used to run test code in a console, and display the results tothe screen, debug output and log file. The class also provides a means oftesting return values or statements, which behaves rather like an assertionand panics when the check fails.18CompatibilityIt is only the wisest and the very stupidest who cannot changeConfuciusI’ve devoted this chapter to compatibility, because it is an importantaspect of software engineering.

If you deliver your software as a set ofinterdependent components, each of which evolves independently, youwill doubtless encounter compatibility issues at some stage.For Symbian, most compatibility issues apply to dependent code, suchas that belonging to third-party developers, which should ideally workequally well on products available today, and with future versions ofSymbian OS. Compatibility must be managed carefully between majorSymbian OS product releases.

For developers delivering Symbian OScode that is not built into ROM, there is the additional complexity ofmanaging compatibility between releases that are built on the sameSymbian OS platform.Let’s consider the basics of delivering a software library – a binarycomponent which performs a well-defined task, such as a set of stringmanipulation functions or a math library. The software’s author typicallypublishes the component’s application programming interface (API) in theform of C++ header files (.h), which are used by a customer’s compiler,and an import library (.lib), which is used by a linker. Often these arealso accompanied by written documentation that describes the correctway to use the library. The API presents, in effect, a contract that definesthe behavior of the component to those that use it (its dependents).Over time, the library may be expanded to deliver additional functionality, or it may be enhanced to remove software defects, make it faster orsmaller, or conform to a new standard.

These modifications may requirechanges to the API; in effect, the contract between the component and itsdependents may need to be re-written. However, before doing this, theimpact of those changes on any dependent code must be assessed. Thenature and implications of a change must be well-understood because,when a library has a number of dependent components in a system, evenan apparently simple modification can have a significant effect.278COMPATIBILITYThis is a fundamental issue of software engineering, and a numberof techniques for writing extensible but compatible software have beendeveloped. Many of the issues associated with compatibility lie outside the scope of this book, but an understanding of the basics willallow you to appreciate the factors which have shaped the evolutionof Symbian OS.

This chapter defines some of the basic terminology ofcompatibility. It then moves on to discuss some of the practical aspects,which will help you to develop code on Symbian OS which can beextended in a controlled manner without having a negative impact onyour external dependents.18.1Forward and Backward CompatibilityCompatibility works in two directions – forward and backward. Whenyou update a component in such a way that other code that used theoriginal version can continue to work with the updated version, youhave made a backward-compatible change. When software that workswith the updated version of your component also works with the originalversion, the changes are said to be forward-compatible.Let’s look at an example: a software house releases a library (v1.0) andan application, A1. Later, it re-releases the library (v2.0) and also releasesa second application, A2, which uses it.

If original copies of A1 continueto work as they did previously with v2.0 of the library, the changes madewere backward-compatible.If the v1.0 version of the library is then reinstalled for some reason,and A2 continues to work with the older library as it did previously withv2.0, the changes were also forward-compatible. This is illustrated inFigure 18.1.Library(version 2.0)BackwardCompatible(Application A1works withversion 2.0 of thelibrary)Update andre-releaseApplicationA1ApplicationA2ForwardCompatible(Application A2works withversion 1.0 of thelibrary)Library(version 1.0)Figure 18.1Forward and backward compatibilityBackward compatibility is usually the primary goal when making incremental releases of a component, with forward compatibility a desirableSOURCE COMPATIBILITY279extra.

Some changes cannot ever be truly forward-compatible, such asbug fixes, which by their nature do not work ”correctly” in releases priorto the fix.There are different levels of compatibility: class-level and library-level.Maintaining compatibility at a class level means ensuring that, amongother things, methods continue to have the same semantics as wereinitially documented, no publicly accessible data is moved, and the sizeof an object of the class does not change (at least, not when a clientis responsible for allocating memory for it). To maintain library-levelcompatibility, you should ensure that the API functions exported by aDLL are at the same ordinal and that the parameters and return values ofeach are still compatible.There are also degrees to which compatibility can be maintained. Thiscan vary from not requiring anything of dependent code (i.e. it can run asit did previously when a new version of the component it uses is installed)to requiring it to be recompiled and/or re-linked.

However, if dependentsource code needs to be changed in any way in order to work with anew release of your component, the changes were incompatible. Pureand simple.Maintaining backward compatibility is the primary goal of an incremental component release.18.2 Source CompatibilityIf you make a change to your component which forces any dependentcode to be changed in order to recompile, the change is sourceincompatible.// orchestra.h// Version 1.0...class CInstrument : public CBase{public:IMPORT_C static CInstrument* NewL();IMPORT_C virtual ∼CInstrument();public:IMPORT_C virtual void PlayL();protected:CInstrument();void ConstructL();private:// ...};280COMPATIBILITYThus, the following change is source-incompatible if dependent codeincludes orchestra.h and uses class CInstrument:// orchestra.h// Version 2.0, renames a class...class CStringInstrument : public CBase{public:IMPORT_C static CStringInstrument* NewL();IMPORT_C virtual ∼CStringInstrument();public:IMPORT_C virtual void PlayL();protected:CStringInstrument();void ConstructL();private:// ...};The only change between version 1.0 and version 2.0 is the change ofclass name from CInstrument to CStringInstrument.

Характеристики

Тип файла
PDF-файл
Размер
2,53 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6294
Авторов
на СтудИзбе
314
Средний доход
с одного платного файла
Обучение Подробнее