Главная » Просмотр файлов » Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356

Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879), страница 12

Файл №779879 Issott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (Symbian Books) 12 страницаIssott_Common Design Patterns for Symbian OS-The Foundations of Smartphone Software_0470516356 (779879) страница 122018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

This can be achieved by calling User::Leave() again withthe same error code.TRAPD(err, iBuffer = iMyClass->AllocBufferL());if(err < KErrNone){if(err == KErrNoMemory){// Resolve error}else{User::Leave(err); // Escalate the error further up the call stack}}ESCALATE ERRORS41Trapping and leaving again is normally only done if a function isonly capable of resolving a subset of possible errors and wishes to trapsome while escalating others.

This should be done sparingly since everyintermediate trap increases the cost of the entire leave operation as thestack unwind has to be restarted.Additional Restrictions on Using Trap–Leave Operations• You should not call a leaving function from within a constructor.This is because any member objects that have been constructed willnot have their destructors called which can cause resource leaks.Instead you should leave from within a ConstructL() methodcalled during the standard Symbian OS two-stage construction processas described by [Babin, 2007, Chapter 4].• You also should not allow a Leave to escape from a destructor.Essentially this means that it is permissible to call leaving functionswithin a destructor so long as they are trapped before the destructorcompletes.

This is for two reasons; the first is that the leave and trapmechanisms are implemented in terms of C++ exceptions and henceif an exception occurs the call stack is unwound. In doing so thedestructors are called for objects that have been placed on the callstack. If the destructors of these objects leave then an abort may occuron some platforms as Symbian OS does not support leaves occurringwhilst a leave is already being handled.20The second reason is that, in principle, a destructor should neverfail.

If a destructor can leave, it suggests that the code has beenpoorly architected. It also implies that part of the destruction process might fail, potentially leading to memory or handle leaks. Oneapproach to solving this is to introduce ‘two-phase destruction’ wheresome form of ShutdownL() function is called prior to deleting theobject. For further information on this, see the Symbian DeveloperLibrary.ConsequencesPositives• Errors can be handled in a more appropriate manner in the layer thatunderstands the error compared to attempting to resolve the errorimmediately.Escalating an error to a design layer with sufficient context to handleit ensures that the error is handled correctly. If this is not done and anattempt is made to handle an error at too low a level, your options for20 Alsoknown as a nested exception.42ERROR-HANDLING STRATEGIEShandling the error are narrowed to a few possibilities which are likelyto be unsuitable.The low-level code could retry the failed operation; it could silentlyignore the error (not normally practical but there may be circumstanceswhen ignoring certain errors is harmless); or it could use Fail Fast (seepage 17).

None of these strategies is particularly desirable especiallythe use of Fail Fast, which should be reserved for faults rather than thedomain or system errors that we are dealing with here.In order to handle an error correctly without escalating it, thecomponent would probably be forced to commit layering violations,e.g., by calling up into the user interface from lower-level code. Thismixing of GUI and service code causes problems with encapsulationand portability as well as decreasing your component’s maintainability. This pattern neatly avoids all these issues.• Less error-handling code needs to be written, which means thedevelopment costs and code size are reduced as well as making thecomponent more maintainable.When using this pattern, you do not need to write explicit code tocheck return codes because the leave and trap mechanism takes careof the process of escalating the error and finding a function higherin the call stack which can handle it for you.

You do not need towrite code to free resources allocated by the function if an erroroccurs because this is done automatically by the cleanup stack priorto the trap harness being invoked. This is especially true if you usea single trap harness at the top of a call stack which is handling anevent.• Runtime performance may be improved.Use of leave–trap does not require any logic to be written to checkfor errors except where trap harnesses are located.

Functions whichcall leaving functions but do not handle the leaves themselves do nothave to explicitly propagate errors upwards. This means that efficiencyduring normal operation improves because there is no need to checkreturn values to see if a function call failed or to perform manualcleanup.Negatives• Traps and leaves are not as flexible as the C++ exception mechanism.A leave can only escalate a single TInt value and hence can onlyconvey error values without any additional context information.In addition, a trap harness cannot be used to catch selected errorvalues. If this is what you need to do then you have to trap allerrors and leave again for those that you can’t resolve at that pointwhich is additional code and a performance overhead for your component.ESCALATE ERRORS43• Runtime performance may get worse when handling errors.A leave is more expensive in terms of CPU usage, compared toreturning an error code from a function, due to the cost of the additional machinery required to manage the data structures associatedwith traps and leaves.

In the Symbian OS v9 Application BinaryInterface (ABI), this overhead is currently minimal because the C++compiler’s exception-handling mechanism is used to implement theleave–trap mechanism which is usually very efficient in moderncompilers.It is best to use leaves to escalate errors which are not expectedto occur many times a second.

Out-of-memory and disk-full errorsare a good example of non-fatal errors which are relatively infrequent but need to be reported and where a leave is usually the mosteffective mechanism. Frequent leaves can become a very noticeableperformance bottleneck. Leaves also do not work well as a generalreporting mechanism for conditions which are not errors. For example,it would not be appropriate to leave from a function that checks forthe presence of a multimedia codec capability when that capabilityis not present. This is inefficient and leads to code bloat due to therequirement on the caller to add a trap to get the result of the check.• Leaves should not be used in real-time code because the leave implementation does not make any real-time guarantees due to the fact thatit involves cleaning up any items on the cleanup stack and freeingresources, usually an unbounded operation.• Without additional support, leaves can only be used to escalate errorswithin the call stack of a single thread.• This pattern cannot be used when writing code that forms part of theSymbian OS kernel, such as device drivers, because the leave–trapoperations are not available within the kernel.Example ResolvedIn the example, an application wished to send data to a peer via UDP.To do this, it was divided into two layers: the UI, dealing with the enduser, and the engine, dealing with Comms-Infras.Engine LayerTo achieve this, we need to open a UDP connection to be able tocommunicate with the peer device.

The RSocket::Open() functionopens a socket and RSocket::Connect() establishes the connection.These operations will fail if Comms-Infras has insufficient resources or thenetwork is unavailable. The engine cannot resolve these errors becauseit is located at the bottom layer of the application design and does not44ERROR-HANDLING STRATEGIEShave the context to try to transparently recover from an error withoutpotentially adversely affecting the end user.

In addition, it has no way ofreleasing resources to resolve local resource contention errors becausethey are owned and used by other parts of the application it does nothave access to.We could implement escalation of the errors by using function returncodes21 as follows:TInt CEngine::SendData(const TDesC8& aData){// Open the socket server and create a socketRSocketServ serv;TInt err = serv.Connect();if(err < KErrNone){return err;}RSocket sock;err = socket.Open(serv,KAfInet,KSockDatagram,KProtocolInetUdp);if(err < KErrNone){serv.Close();return err;}// Connect to the localhost.TInetAddr addr;addr.Input(_L("localhost"));addr.SetPort(KTelnetPort);TRequestStatus status;sock.Connect(addr, status);User::WaitForRequest(status);if(status.Int() < KErrNone){sock.Close();serv.Close();return status.Int();}// Send the data in a UDP packet.sock.Send(aData, 0, status);User::WaitForRequest(status);sock.Close();serv.Close();return status.Int();}21Note that the code is given to show how the RSocket API handles errors and is notproduction quality.

For instance, a normal application would use Active Objects (seepage 133) instead of TRequestStatus objects.ESCALATE ERRORS45However, as you can see, the error-handling code is all mixed upwith the normal flow of execution making it more difficult to maintain.A better approach would be to use the Symbian OS error-handlingfacilities, resulting in a much more compact implementation:void CEngine::SendDataL(const TDesC8& aData){// Open the socket server and create a socketRSocketServ serv;User::LeaveIfError(serv.Connect());CleanupClosePushL(serv);RSocket sock;User::LeaveIfError(sock.Open(serv,KAfInet,KSockDatagram,KProtocolInetUdp));CleanupClosePushL(sock);// Connect to the localhost.TInetAddr addr;addr.Input(_L("localhost"));addr.SetPort(KTelnetPort);TRequestStatus status;sock.Connect(addr, status);User::WaitForRequest(status);User::LeaveIfError(status.Int());// Send the data in a UDP packet.sock.Send(aData, 0, status);User::WaitForRequest(status);User::LeaveIfError(status.Int());CleanupStack::PopAndDestroy(2); // sock and serv}Note that in the above we rely on the fact that RSocket::Close()does not leave.

This is because we use CleanupClosePushL() totell the cleanup stack to call Close() on both the RSocketServ andRSocket objects if a leave occurs while they’re on the cleanup stack.This is a common property of Symbian OS functions used for cleanupfunctions, such as Close(), Release() and Stop(). There is nothinguseful that the caller can do if one of these functions fails, so errors needto be handled silently by them.UI LayerIn this case, the application implementation relies on the applicationframework to provide the top-level trap harness to catch all errors escalated upwards by the Engine. When an error is caught by the trap it thencalls the CEikAppUi::HandleError() virtual function.

By default,this displays the error that occurred in an alert window to the end user. If46ERROR-HANDLING STRATEGIESyou’ve put everything on the cleanup stack then this may be all you needto do. However, an alternative is to override the function and providea different implementation. Note that HandleError() is called with anumber of parameters in addition to the basic error:TErrorHandlerResponse CEikAppUi::HandleError(TIntconst SExtendedError&TDes&TDes&aError,aExtErr,aErrorText,aContextText)These parameters are filled in by the application framework and gosome way to providing extra context that might be needed when resolvingthe error at the top of the application’s call stack.

By relying on this, thelower layers of the application can escalate any errors upwards to the toplayer in the design to handle the error. Use of this pattern enables errorsto be resolved appropriately and minimizes the amount of error-handlingcode which needs to be written.Other Known UsesThis pattern is used extensively within Symbian OS so here are just acouple of examples:• RArrayThis is just one of many classes exported from euser.dll that leaveswhen it encounters an error. Basic data structures like these don’t haveany knowledge of why they’re being used so they can’t resolve anyerrors.

Interestingly, this class provides both a leave and a functionreturn variant of each of its functions. This is so that it can be usedkernel-side, where leaves cannot be used, and user-side, where leavesshould be used to simplify the calling code as much as possible.• CommsDatCommsDat is a database engine for communication settings suchas network and bearer information. It is rare for an error to occurwhen accessing a CommsDat record unless the record is missing.Hence by using leaves to report errors, its clients can avoid having towrite excessive amounts of error-handling code.

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

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

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

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